def send_email(self, user_external_id: str, sender_email: str, sender_name: str, to_email: str, subject: str, plain_text_content: str, html_content: str) -> Tuple[EmailResult, str]: # https://github.com/sendgrid/sendgrid-python/blob/master/examples/helpers/mail_example.py#L16 mail_params = { 'from_email': From(sender_email, sender_name), 'to_emails': to_email, 'subject': Subject(subject), } if plain_text_content: mail_params['plain_text_content'] = PlainTextContent( plain_text_content) if html_content: mail_params['html_content'] = HtmlContent(html_content) message = Mail(**mail_params) response = self._get_sendgrid_client().send(message) if response and (response.status_code in [200, 202, 201]): external_id = response.headers['X-Message-Id'] # External From, Subject etc are not Json Serializable mail_params['from_email'] = (sender_email, sender_name) mail_params['subject'] = subject if plain_text_content: mail_params['plain_text_content'] = plain_text_content if html_content: mail_params['html_content'] = html_content BaseEmail.create(mail_params, to_email, self.get_type(), EmailResult.SENT, external_id, user_external_id) return EmailResult.SENT, external_id return EmailResult.FAILED, None
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)
def send_messages(self, email_messages): sg = sendgrid.SendGridAPIClient(api_key=self.api_key) for email_message in email_messages: mail = Mail( from_email=email_message.from_email, to_emails=email_message.to, subject=email_message.subject, html_content=HtmlContent(email_message.body), ) for attachment in email_message.attachments: mail.add_attachment(Attachment( file_name=attachment[0], file_content=base64.b64encode(attachment[1]).decode(), file_type=attachment[2], )) try: response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code // 100 != 2: error_message = ( f'Email "{email_message.subject}" was not sent to {email_message.to}. ' f'Status is {response.status_code}' ) if self.fail_silently: logger.error(error_message) else: raise SendGridBadStatusError(error_message) except HTTPError as error: if self.fail_silently: if type(error) == ForbiddenError: logger.exception(f'Email {email_message.subject} was not sent to {email_message.to} - {error.to_dict}') else: logger.exception(f'Email {email_message.subject} was not sent to {email_message.to} - {error}') else: raise
def send(): message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='Sending with Twilio SendGrid is Fun', html_content=HtmlContent(request.args["html_content"])) sg = SendGridAPIClient('SENDGRID_API_KEY') sg.send(message)
def send(recipients: Union[Tuple[Tuple[str, str]], Tuple[str, str]], subject: str, body_html: Optional[str], body_text: str) -> bool: """Send an email from the configured address. `recipients` is a list of tuples like `[(address, name),...]` or just a single tuple like `(address, name)`. Does not check for address validity. If `body_text` is None, it will be derived from `body_html`. if `body_html` is None but `body_text` is provided, no HTML part will be sent. Returns True on success, false otherwise. Does not throw exception. """ if config.DEMO: # Emails to users are disabled to prevent abuse. return True if not recipients: return True if isinstance(recipients[0], str): # We were passed just `(address, name)`.s recipients = [recipients] if not body_text and not body_html: raise Exception( 'emailer.send: body_text or body_html must be provided') elif body_html and not body_text: h2t = html2text.HTML2Text() h2t.body_width = 0 body_text = h2t.handle(body_html) sg = SendGridAPIClient(api_key=config.SENDGRID_API_KEY) to = [] for r in recipients: to.append(To(r[0], r[1])) message = Mail(from_email=From(config.MASTER_EMAIL_SEND_ADDRESS, name=config.MASTER_EMAIL_SEND_NAME), to_emails=to, subject=Subject(subject), plain_text_content=PlainTextContent(body_text), html_content=HtmlContent(body_html) if body_html else None) response = sg.client.mail.send.post(request_body=message.get()) if response.status_code not in (200, 202): # The expected response code is actually 202, but not checking for 200 as well feels weird. logging.error( f"emailer.send fail: {response.status_code} | {response.body} | {response.headers}" ) return False # Body is expected to be empty on success, but we'll check it anyway. logging.info( f"emailer.send success: {response.status_code} | {response.body}") return True
def test_error_is_not_raised_on_to_emails_set_to_a_tuple(self): from sendgrid.helpers.mail import (PlainTextContent, HtmlContent) self.maxDiff = None to_emails = ('*****@*****.**', 'Example To Name 0') Mail(from_email=From('*****@*****.**', 'Example From Name'), to_emails=to_emails, subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>'))
def index(request): sendgrid_client = SendGridAPIClient(api_key=SENDGRID_API_KEY) from_email = From(TICO_CHURCH_EMAIL) to_email = To(TICO_DEV_GMAIL) subject = 'Check Out This SendGrid Magic!' plain_text_content = PlainTextContent('How dope is this?') html_content = HtmlContent('<strong>It is SO dope!</strong>') message = Mail(from_email, to_email, subject, plain_text_content, html_content) response = sendgrid_client.send(message=message) return HttpResponse('Email Sent!')
def send_email(to, subject, template, **kwargs): app = current_app._get_current_object() sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) from_email = app.config['MAIL_SENDER'] html_body = render_template(template + ".html", **kwargs) plain_body = render_template(template + ".txt", **kwargs) mail = Mail(from_email=app.config['MAIL_SENDER'], to_emails=[To(to)], subject=Subject(subject), html_content=HtmlContent(html_body), plain_text_content=PlainTextContent(plain_body)) return sg.client.mail.send.post(request_body=mail.get())
def send_mail(from_email, to_emails, subject, content): message = Mail(from_email=from_email, to_emails=To(to_emails), subject=subject, html_content=HtmlContent(content)) try: api_key = current_app.config["SENDGRID_API_KEY"] sg = SendGridAPIClient(api_key) response = sg.send(message) except Exception as e: print(e)
def send_email(subject, content, to_addresses): html_content = render_template('email.html', content=content) message = Mail(from_email='*****@*****.**', to_emails=map(lambda e: str(e), to_addresses), subject=subject, html_content=HtmlContent(html_content)) workbench = db.WorkBench.query().get() sg = SendGridAPIClient(workbench.email_api_key) response = sg.send(message) if response.status_code > 299: logging.error('unable to send email subject: %s status: %d' % (subject, response.status_code)) else: logging.info('sent email subject: %s' % subject)
def test_send_a_single_email_to_multiple_recipients(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None to_emails = [ To('*****@*****.**', 'Example To Name 0'), To('*****@*****.**', 'Example To Name 1') ] message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=to_emails, subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name 0" }, { "email": "*****@*****.**", "name": "Example To Name 1" } ] } ], "subject": "Sending with SendGrid is Fun" }'''))
def send_email(self): """Sends alert email and clears the current email draft.""" if not self.write_to_email or not self.messages_to_email: return html_message_body = self.generate_email_body() message = Mail(from_email=From(self.sender_email, 'Cloud Accelerators Alert Manager'), to_emails=[To(self.recipient_email)], subject=AlertHandler.generate_email_subject(), plain_text_content=PlainTextContent('empty'), html_content=HtmlContent(html_message_body)) response = self.sendgrid.send(message) self._log( 'Email send attempt response: {}\n{}'.format( response.status_code, response.headers), logging.INFO) self.messages_to_email.clear()
def send_email(to, subject, content): try: sg = sendgrid.SendGridAPIClient( api_key=settings.get('SENDGRID_API_KEY')) from_email = Email(settings.get('DEFAULT_FROM_EMAIL')) to_email = To(to) html_content = HtmlContent(content) mail = Mail(from_email, to_email, subject, html_content) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 200: return True return False except Exception as e: raise SendEmailError(e)
def test_value_error_is_raised_on_to_emails_set_to_list_of_lists(self): from sendgrid.helpers.mail import (PlainTextContent, HtmlContent) self.maxDiff = None to_emails = [['*****@*****.**', 'Example To Name 0'], ['*****@*****.**', 'Example To Name 1']] with self.assertRaises(ValueError): Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=to_emails, subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>' ))
def test_unicode_values_in_substitutions_helper(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) message.substitution = Substitution('%city%', u'Αθήνα', p=1) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] }, { "substitutions": { "%city%": "Αθήνα" } } ], "subject": "Sending with SendGrid is Fun" }'''))
def send_email(from_address, to_address, subject, body): mail = Mail( from_email=From(from_address, "Districtr"), subject=Subject(subject), to_emails=To(to_address), html_content=HtmlContent(body), ) client = SendGridAPIClient( api_key=current_app.config["SENDGRID_API_KEY"]).client if current_app.config.get("SEND_EMAILS", True) is False: print("Sending mail", mail) return response = client.mail.send.post(request_body=mail.get()) if response.status_code >= 300: raise ApiException("Unable to send email.", status=500)
def test_single_email_to_a_single_recipient_content_reversed(self): """Tests bug found in Issue-451 with Content ordering causing a crash """ from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail() message.from_email = From('*****@*****.**', 'Example From Name') message.to = To('*****@*****.**', 'Example To Name') message.subject = Subject('Sending with SendGrid is Fun') message.content = HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>') message.content = PlainTextContent( 'and easy to do anywhere, even with Python') self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] } ], "subject": "Sending with SendGrid is Fun" }'''))
def build_hello_email(): ## Send a Single Email to a Single Recipient import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException message = Mail(from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>')) try: print(json.dumps(message.get(), sort_keys=True, indent=4)) return message.get() except SendGridException as e: print(e.message)
def build_hello_email(): ## Send a Single Email to a Single Recipient import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) try: print(json.dumps(message.get(), sort_keys=True, indent=4)) return message.get() except SendGridException as e: print(e.message) for cc_addr in personalization['cc_list']: mock_personalization.add_to(cc_addr) for bcc_addr in personalization['bcc_list']: mock_personalization.add_bcc(bcc_addr) for header in personalization['headers']: mock_personalization.add_header(header) for substitution in personalization['substitutions']: mock_personalization.add_substitution(substitution) for arg in personalization['custom_args']: mock_personalization.add_custom_arg(arg) mock_personalization.subject = personalization['subject'] mock_personalization.send_at = personalization['send_at'] return mock_personalization
def send_email(self): """Sends alert email and clears the current email draft.""" if not self.write_to_email or not self.messages_to_email: return html_message_body = 'New errors in test suite for {}:'.format( self.project_id) html_message_body += '<ul>' for logs_link in self.messages_to_email.keys(): html_message_body += '<li>{}:'.format( 'General errors' if logs_link == _NO_LOGS else \ util.test_name_from_logs_link(logs_link)) html_message_body += '<ul>' for message in self.messages_to_email[logs_link]: html_message_body += '<li>{}</li>'.format(message) # If the error was specific to a certain test, include links to quickly # access the logs from that test. if logs_link != _NO_LOGS: html_message_body += '<li><a href="{}">Stackdriver logs for this ' \ 'run of the test</a></li>'.format(logs_link) html_message_body += '<li>Command to download plaintext logs: ' \ '<code style="background-color:#e3e3e3;">' \ '{}</code></li>'.format( util.download_command_from_logs_link( logs_link)) html_message_body += '</ul>' html_message_body += '</li>' html_message_body += '</ul>' message = Mail(from_email=From(self.sender_email, 'Cloud Accelerators Alert Manager'), to_emails=[To(self.recipient_email)], subject=Subject( 'Errors in ML Accelerators Tests at {}'.format( datetime.now().strftime("%Y/%m/%d %H:%M:%S"))), plain_text_content=PlainTextContent('empty'), html_content=HtmlContent(html_message_body)) response = self.sendgrid.send(message) self._log( 'Email send attempt response: {}\n{}'.format( response.status_code, response.headers), logging.INFO) self.messages_to_email.clear()
def create_email(address, subject, template_name, context): 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) content = HtmlContent(html_to_send) from_email = From("*****@*****.**", "Unsub Team") to_email = To(address) to_emails = [to_email] if "mmu.ac.uk" in address: to_emails += [Cc("*****@*****.**")] email = Mail(from_email=from_email, subject=Subject(subject), to_emails=to_emails, html_content=content) logger.info((u'sending email "{}" to {}'.format(subject, address))) return email
def send_user_info(self, username, password): html_text = f""" <html> <body> <div style=" max-width: 60%; margin: 0 auto; "> <p>Hello,</p> <p>Your account has been created and ready to use. In order to obtain access to your account please click <a href="https://jomari-designs-app.herokuapp.com/login">here</a> and enter the details below: </p> <ul> <li>username: {username}</li> <li>password: {password}</li> </ul> </div> </body> </html> """ from_email = From("*****@*****.**") to_email = To(self._receiver) subject = Subject('Welcome To Jomari Designs') html_content = HtmlContent(html_text) soup = BeautifulSoup(html_text, features='html.parser') plain_text = soup.get_text() plain_text_content = Content("text/plain", plain_text) message = Mail(from_email, to_email, subject, plain_text_content, html_content) response = self.sendgrid_client.send(message=message) return response
def send_email_base(self, from_email, to_emails, subject, html_content): message = Mail(from_email=From(from_email), to_emails=[To(to_email) for to_email in to_emails], subject=Subject(subject), html_content=HtmlContent(html_content)) return self.__sg.send(message)
def test_single_email_to_a_single_recipient_with_dynamic_templates(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) message.dynamic_template_data = DynamicTemplateData({ "total": "$ 239.85", "items": [{ "text": "New Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png", "price": "$ 79.95" }, { "text": "Old Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png", "price": "$ 79.95" }, { "text": "Blue Line Sneakers", "image": "https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png", "price": "$ 79.95" }], "receipt": True, "name": "Sample Name", "address01": "1234 Fake St.", "address02": "Apt. 123", "city": "Place", "state": "CO", "zip": "80202" }) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "dynamic_template_data": { "address01": "1234 Fake St.", "address02": "Apt. 123", "city": "Place", "items": [ { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/8dda1131320a6d978b515cc04ed479df259a458d5d45d58b6b381cae0bf9588113e80ef912f69e8c4cc1ef1a0297e8eefdb7b270064cc046b79a44e21b811802.png", "price": "$ 79.95", "text": "New Line Sneakers" }, { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/3629f54390ead663d4eb7c53702e492de63299d7c5f7239efdc693b09b9b28c82c924225dcd8dcb65732d5ca7b7b753c5f17e056405bbd4596e4e63a96ae5018.png", "price": "$ 79.95", "text": "Old Line Sneakers" }, { "image": "https://marketing-image-production.s3.amazonaws.com/uploads/00731ed18eff0ad5da890d876c456c3124a4e44cb48196533e9b95fb2b959b7194c2dc7637b788341d1ff4f88d1dc88e23f7e3704726d313c57f350911dd2bd0.png", "price": "$ 79.95", "text": "Blue Line Sneakers" } ], "name": "Sample Name", "receipt": true, "state": "CO", "total": "$ 239.85", "zip": "80202" }, "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] } ], "subject": "Sending with SendGrid is Fun" }'''))
def test_multiple_emails_to_multiple_recipients(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent, Substitution) self.maxDiff = None to_emails = [ To(email='*****@*****.**', name='Example Name 0', substitutions=[ Substitution('-name-', 'Example Name Substitution 0'), Substitution('-github-', 'https://example.com/test0'), ], subject=Subject('Override Global Subject')), To(email='*****@*****.**', name='Example Name 1', substitutions=[ Substitution('-name-', 'Example Name Substitution 1'), Substitution('-github-', 'https://example.com/test1'), ]) ] global_substitutions = Substitution('-time-', '2019-01-01 00:00:00') message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=to_emails, subject=Subject('Hi -name-'), plain_text_content=PlainTextContent( 'Hello -name-, your URL is -github-, email sent at -time-'), html_content=HtmlContent( '<strong>Hello -name-, your URL is <a href=\"-github-\">here</a></strong> email sent at -time-' ), global_substitutions=global_substitutions, is_multiple=True) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "Hello -name-, your URL is -github-, email sent at -time-" }, { "type": "text/html", "value": "<strong>Hello -name-, your URL is <a href=\"-github-\">here</a></strong> email sent at -time-" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "substitutions": { "-github-": "https://example.com/test1", "-name-": "Example Name Substitution 1", "-time-": "2019-01-01 00:00:00" }, "to": [ { "email": "*****@*****.**", "name": "Example Name 1" } ] }, { "subject": "Override Global Subject", "substitutions": { "-github-": "https://example.com/test0", "-name-": "Example Name Substitution 0", "-time-": "2019-01-01 00:00:00" }, "to": [ { "email": "*****@*****.**", "name": "Example Name 0" } ] } ], "subject": "Hi -name-" }'''))
## Send a Single Email to a Single Recipient import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException message = Mail( from_email=From('*****@*****.**', 'DX'), to_emails=To('*****@*****.**', 'Elmer Thomas'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) try: print(json.dumps(message.get(), sort_keys=True, indent=4)) sendgrid_client = SendGridAPIClient( api_key=os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.send(message=message) print(response.status_code) print(response.body) print(response.headers) except SendGridException as e: print(e.message) # Send a Single Email to Multiple Recipients import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException
def index(request): """ Posts method: list all objects on the database + hide draft versions to non-staff users """ today = timezone.now().date() form = EmailPostForm(request.POST or None) if form.is_valid() and request.method == "POST": cd = form.cleaned_data from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, HtmlContent message = Mail( from_email=cd["email"], to_emails=settings.EMAIL_HOST_RECIPIENT, subject=cd["subject"], html_content=HtmlContent( template.format( str(cd["firstname"]) + " " + str(cd["lastname"]), str(cd["message"]), str(cd["subject"]), str(cd["urgency"]), str(cd["pricerange"]), )), ) try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) if cd["sendcc"] is True: from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, HtmlContent sg = SendGridAPIClient(settings.SENDGRID_API_KEY) message2 = Mail( from_email="*****@*****.**", to_emails=cd["email"], subject=cd["subject"], html_content=HtmlContent( template.format( str(cd["firstname"]) + " " + str(cd["lastname"]), str(cd["message"]), str(cd["subject"]), str(cd["urgency"]), str(cd["pricerange"]), )), ) response = sg.send(message2) except Exception as e: messages.error(request, f"Your message could not be sent. {e}") return HttpResponseRedirect("/") messages.success( request, "Your message was successfully sent to: " + settings.EMAIL_HOST_RECIPIENT, ) return HttpResponseRedirect("/") if request.method == "POST": form = EmailPostForm() return render(request, "index.html", {"today": today, "form": form})