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_email(email_address, email_subject, email_content, from_email): print("Enviando email: " + str(email_subject)) sg = sendgrid.SendGridAPIClient(API_KEY_SENDGRID) content = PlainTextContent(email_content) mail = Mail(from_email, email_address, email_subject, content) response = sg.send(mail) print("SendGrid email aviso response status code: " + str(response.status_code) + "\n\n\n")
def send_email(email, subject, content): message = Mail(from_email='*****@*****.**', to_emails=email, subject=subject, plain_text_content=PlainTextContent(content)) try: send_mail_via_sendgrid(message) except ForbiddenError: pass
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 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 sendgrid_plain_email(recipient): sg = sendgrid.SendGridAPIClient(api_key=settings.SENDGRID_API_KEY) from_email = Email("*****@*****.**") to_email = To(recipient) subject = "Newsletter Email" plain_text_content = PlainTextContent('HNG Internship Newsletter Email') # html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>') # message.cc = Cc('*****@*****.**') # message.cc = Bcc('*****@*****.**') mail = Mail(from_email, to_email, subject, plain_text_content) response = sg.client.mail.send.post(request_body=mail.get()) return response
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): reset_url = settings.FRONT_URL + 'newPassword/' + reset_password_token.key reset_token_message = f'Aby zresetować hasło, kliknij w poniższy link i postępuj zgodnie ze wskazówkami:\n{reset_url}\n\n' + \ 'Jeśli nie prosiłeś o zmianę hasła, zignoruj ten link i skontaktuj się z pomocą techniczną.\n\n Pozdrawiamy\n Zespół usamodzielnieni.pl' message = Mail(from_email='*****@*****.**', to_emails=reset_password_token.user.email, subject='Usamodzielnieni -- resetowanie hasła', plain_text_content=PlainTextContent(reset_token_message)) send_mail_via_sendgrid(message)
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 send_email(sendgrid_api_key: Text, from_email: Text, to_emails: List[Text], subject: Text, email_text: Text) -> None: sg = sendgrid.SendGridAPIClient(api_key=sendgrid_api_key) content = PlainTextContent(email_text) mail = Mail(from_email=from_email, to_emails=to_emails, subject=subject, plain_text_content=content) sg.send(mail) print( f"Sent email from {from_email} to {to_emails} with subject '{subject}' and text: '{email_text}'" )
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 sendmail(request): sendgrid_client = SendGridAPIClient( api_key=environ.get('SENDGRID_API_KEY')) from_email = From(environ.get('ADMIN_EMAIL')) to_email = To(environ.get('ADMIN_EMAIL')) subject = request.POST['fname'] + ' ' + \ request.POST['lname'] + ' - phone num: ' + request.POST['phone'] plain_text_content = PlainTextContent(request.POST['message']) message = Mail(from_email, to_email, subject, plain_text_content) response = sendgrid_client.send(message=message) print(response) return render(request, 'pages/contact_form.html', {'email_sent': True})
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 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 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 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 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 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 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 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-" }'''))
import os import json import python_http_client from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException API_KEY = 'Hn6D' TEMPLATE_ID = 'bf513' message = Mail(subject=Subject("my subject"), from_email=From('*****@*****.**', 'sender'), to_emails=To('*****@*****.**', 'Vitalii')) # message.template_id=TEMPLATE_ID # message.dynamic_template_data = {"unsubscribe": "<<< unsubscribe custom text >>>", "unsubscribe_preferences": "<<< unsubscribe_preferences custom text >>>"} message.content = PlainTextContent("this is test content") try: sendgrid_client = SendGridAPIClient(API_KEY) print(json.dumps(message.get(), sort_keys=True, indent=4)) response = sendgrid_client.send(message=message) if 300 > response.status_code >= 200: print(response.status_code) print(response.body) except SendGridException as e: print(e.message) except python_http_client.exceptions.HTTPError as e: print(e.body)
## 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
PSWD = os.environ.get("API_KEY") #open a csv file in the same folder containing names and email addresses csvFile = open("email-list.csv", "r", newline="") fileData = csv.reader(csvFile) next(fileData) #skip csv file header for name, email in fileData: #parse each line in csv file and capture name and email #format email message message = Mail( from_email= '*****@*****.**', #email you want to appear the message sent from to_emails=email, #addresses email from csv file subject=("Test email"), #message body plain_text_content=PlainTextContent(f'''Hello {name}, this is a test email sent from my pc using python and sendGrid APIs''' )) try: sg = SendGridAPIClient(PSWD) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(e)) csvFile.close()