def sendExperimentResults(config): try: from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition, ContentId) message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject=f'Experiment results: {config.configurationDirectory}', html_content= f'These are your results for {config.configurationDirectory}. Please see the attached charts.' ) for file in config.listAllFilesInFolder("charts"): data = config.loadKwolaFileData("charts", file) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('image/png') attachment.file_name = FileName(file) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId(file) message.add_attachment(attachment) videoFiles = config.listAllFilesInFolder("debug_videos") videoFiles = sorted( videoFiles, key=lambda fileName: pathlib.Path( os.path.join(config.configurationDirectory, "debug_videos", fileName)).stat().st_mtime, reverse=True) for file in videoFiles[:2]: data = config.loadKwolaFileData("debug_videos", file) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('video/mpeg') attachment.file_name = FileName(file) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId(file) message.add_attachment(attachment) if 'sendgrid_api_key' in config: apiKey = config['sendgrid_api_key'] elif 'SENDGRID_API_KEY' in os.environ: apiKey = os.environ.get('SENDGRID_API_KEY') else: getLogger().error( "There was no API key provided for Sendgrid. Please set sendgrid_api_key within your config.json file." ) return sg = SendGridAPIClient(apiKey) response = sg.send(message) except Exception: getLogger().error(traceback.format_exc())
def send(self, config, subject, body, img, row): content = Content("text/html", body) attachment = Attachment() attachment.content = img attachment.type = "image/jpeg" attachment.filename = "qrcode.jpg" attachment.disposition = "inline" attachment.content_id = "qrcode" fromaddr = Email(config.from_email) toaddr = Email(row['email']) mail = Mail(fromaddr, subject, toaddr, content) mail.add_attachment(attachment) try: response = self.sg.client.mail.send.post(request_body=mail.get()) except urllib.HTTPError as err: print(err.read()) exit() print(response.status_code) print(response.body) print(response.headers)
def sendgrid_attachments(self, bodyobj): to_emails = self.transform_to_emails() message = Mail(from_email=('<email_change>', '<name_change>'), to_emails=to_emails, subject=self.subject, html_content=bodyobj['body']) # attachments attchments = [] for fle in bodyobj['logfiles']: if fle == 'None': continue else: with open(fle, 'rb') as f: dta = f.read() fname = os.path.basename(f.name) encoded = base64.b64encode(dta).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) # text/plain text/comma-separated-values attachment.file_type = FileType('text/plain') attachment.file_name = FileName(fname) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') attchments.append(attachment) message.attachment = attchments try: sendgrid_client = SendGridAPIClient(self.apikey) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def send(filename, job, city, email_receiver, sendgrid_api_key, sendgrid_email_sender): try: sg = sendgrid.SendGridAPIClient(api_key=sendgrid_api_key) message = Mail( from_email=sendgrid_email_sender, to_emails=email_receiver.replace(',', ''), subject=f"LinkedIn: {job} jobs in {city} (Weekly).", html_content= f"Automated report for {job} jobs in {city} generated on {datetime.datetime.now()}." ) with open(filename, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/csv') attachment.file_name = FileName(filename) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('') message.attachment = attachment response = sg.client.mail.send.post(request_body=message.get()) print(f"\n\033[1m📩 Email sent successfully to {email_receiver}\033[0m") except Exception as e: print("Error:", e) print( "\n\033[1m❌ An error occurred while trying to send the email!\033[0m" )
def send_styled_email(to_email): load_dotenv(dotenv_path='sendgrid.env') message = Mail( from_email='*****@*****.**', to_emails=to_email, subject='Here is your Stylized image!', html_content= '<strong>and easy to do anywhere, even with Python</strong>') file_path = 'output.jpg' with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/jpg') attachment.file_name = FileName('output.jpg') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sendgrid_client = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def send_email(email_to): message = Mail( from_email = '*****@*****.**', to_emails = email_to, subject='Mango Investment CSV File', html_content='<strong>Here is the file you requested.</strong>') file_path = os.path.join(os.getcwd(), "trades.csv") with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/csv') attachment.file_name = FileName('trades.csv') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sg = SendGridAPIClient('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') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return response.status_code except Exception as e: print(e.message)
def send_email(subject="Workout", html="<p>Today's Workout</p>", pdf="workout.pdf"): client = SendGridAPIClient( SENDGRID_API_KEY) #> <class 'sendgrid.sendgrid.SendGridAPIClient> message = Mail(from_email=MY_EMAIL, to_emails=MY_EMAIL, subject=subject, html_content=html) #attaches the PDF we generated earlier file_path = 'workout.pdf' with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName('JuicyLiftWorkout.pdf') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment #send email try: response = client.send(message) return response except Exception as e: print("OOPS", e.message) return None
def send_zip(self, file_name: str, data: bytes) -> bool: # create message message = Mail(self.from_email, self.to_email, self.subject, self.content) # create attachment file_type = 'GED file' encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType(file_type) attachment.file_name = file_name attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment # This code is for testing purposes. # Allows to test the class above without sending mail. # If a value in "SENDGRID_TEST" environment equals to "True" this function will return boolean True # otherwise this function will return boolean False. if os.environ.get("SENDGRID_TEST") is not None: return os.environ.get("SENDGRID_TEST") == "True" # send try: sg = SendGridAPIClient(self.api_key) response = sg.send(message) logger.info( "Sent gedcom successfully with response code: {}".format( response.status_code)) return True except Exception: logger.exception("Failed to sent gedcom") return False
def send_email(email_to): message = Mail( from_email='*****@*****.**', to_emails=email_to, subject='Crypto Investment CSV File', html_content='<strong>Here is the file you requested.</strong>') file_path = os.path.join(os.getcwd(), "trades.csv") with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/csv') attachment.file_name = FileName('trades.csv') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sg = SendGridAPIClient( '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' ) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return response.status_code except Exception as e: print(e.message)
def sendlog(): sg = sendgrid.SendGridAPIClient(apikey=os.environ['SENDGRID_API_KEY']) contentString = "bi-weekly refactoring roundup" attachment = Attachment() attachment.content = encodefile('log/out.txt') attachment.type = 'text/plain' attachment.filename = 'log/out.txt' attachment.disposition = 'attachment' attachment.content_id = 'log' from_email = Email('*****@*****.**') to_email = Email('*****@*****.**') subject = 'refactoring roundup' content = Content('text/plain', contentString) mail = Mail(from_email, subject, to_email, content) mail.add_attachment(attachment) mail.personalizations[0].add_cc(Email('*****@*****.**')) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers)
def sendMailWithAttachment(context): # print(context) html_version = 'email/email.html' message = Mail( from_email='*****@*****.**', to_emails=context['emails'], subject="Reg: Payment remittance for {} ${} {} Vendor : {}".format( context["clearing_date"], context["amount"], context["currency"], context["supplier"]), html_content=render_to_string(html_version, {'context': context})) with open(context['attachment'], 'rb') as f: data = f.read() f.close() print(data) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('text/csv') attachment.file_name = FileName(context['attachment']) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('REMITTANCE') message.add_attachment(attachment) try: sg = SendGridAPIClient( "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" ) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e) # sendMailWithAttachment()
def send_email(self, email, pdf_path): message = Mail( from_email="Aditya Raman <*****@*****.**>", to_emails=email, subject="[MSP Testing] Testing for Attendee's Certificate", html_content=" Sending the attachment<br>", ) file_path = pdf_path file_name = list(file_path.split("/"))[-1] with open(file_path, "rb") as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType( "application/pdf") # FileType("image/png") attachment.file_name = FileName(file_name) attachment.disposition = Disposition("attachment") attachment.content_id = ContentId("Microsoft Student Partner") message.attachment = attachment try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) return response except Exception as e: print(e) return e
def send_email(subject="Unemployment Data", html="<p>Unemployment Data</p>", png=image_name): client = SendGridAPIClient( SENDGRID_API_KEY) #> <class 'sendgrid.sendgrid.SendGridAPIClient> message = Mail(from_email=MY_EMAIL, to_emails=MY_EMAIL, subject=subject, html_content=html) #Attaches the PNG we Generated Earlier Using Selenium with open(image_name, 'rb') as f: image = f.read() f.close() image_encoded = base64.b64encode(image).decode() attachment = Attachment() attachment.file_content = FileContent(image_encoded) attachment.file_type = FileType('image/png') attachment.file_name = FileName('unemployment_rate.png') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment #Send Email try: response = client.send(message) print(response.status_code) print(response.body) return response except Exception as e: print("OOPS", e.message) return None
def SendMail(ImgFileName): message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='SURVEILLANCE ALERT: Unauthorized Access of MAIN GATE', html_content= '<strong>REPORT FOR INTRUSION DETECTION: Person has crossed the area, Here we attached a reference image </strong>' ) data = cv2.imencode('.jpg', ImgFileName)[1].tostring() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/jpg') attachment.file_name = FileName('alert.jpg') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sendgrid_client = SendGridAPIClient( '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' ) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def email(self, to_email, template, data): # We always append on the destination url to help. data['url'] = secret.get()['url'] # Build the mail object & send the email. # Attach the ics to the email c = generate_ics() message = Mail(from_email=self.from_email, to_emails=to_email) message.dynamic_template_data = data message.template_id = self.templates[template] encoded = base64.b64encode(str(c).encode('utf-8')).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('text/calendar') attachment.file_name = FileName('shift.ics') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sendgrid_client = SendGridAPIClient(api_key=self.api_key) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def EmergencyMail(mail_subject, html_content, file_path): """This function utilizes SendGrid Api to send emergcency signals as email to the necessary agencies""" message = Mail(from_email=current_app.config['APP_EMAIL'], to_emails=current_app.config['AGENT_EMAILS'].split(' '), subject=mail_subject, html_content=html_content) with open(file_path, 'rb') as f: data = f.read() f.close() # encode file encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/xls') attachment.file_name = FileName('data.xls') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('PatientData') message.attachment = attachment try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) resp = sg.send(message) return True except HTTPError as e: #print(f"{resp.status_code}'\n'{resp.body}'\n'{resp.headers}") print(e.to_dict) return False else: print(e.to_dict) return False
def _create_sg_attachment(self, django_attch: DjangoAttachment) -> Attachment: """ Handles the conversion between a django attachment object and a sendgrid attachment object. Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure that attachments get properly instantiated. """ def set_prop(attachment, prop_name, value): if SENDGRID_5: setattr(attachment, prop_name, value) else: if prop_name == "filename": prop_name = "name" setattr(attachment, "file_{}".format(prop_name), value) sg_attch = Attachment() if isinstance(django_attch, MIMEBase): filename = django_attch.get_filename() if not filename: ext = mimetypes.guess_extension( django_attch.get_content_type()) filename = "part-{0}{1}".format(uuid.uuid4().hex, ext) set_prop(sg_attch, "filename", filename) # todo: Read content if stream? set_prop(sg_attch, "content", django_attch.get_payload().replace("\n", "")) # Content-type handling. Includes the 'method' param. content_type = django_attch.get_content_type() method = django_attch.get_param("method") if method: if content_type.strip()[-1] != ";": content_type += ";" content_type += f" method={method};" set_prop(sg_attch, "type", content_type) content_id = django_attch.get("Content-ID") if content_id: # Strip brackets since sendgrid's api adds them if content_id.startswith("<") and content_id.endswith(">"): content_id = content_id[1:-1] # These 2 properties did not change in v6, so we set them the usual way sg_attch.content_id = content_id sg_attch.disposition = "inline" else: filename, content, mimetype = django_attch set_prop(sg_attch, "filename", filename) # todo: Read content if stream? if isinstance(content, str): content = content.encode() set_prop(sg_attch, "content", base64.b64encode(content).decode()) set_prop(sg_attch, "type", mimetype) return sg_attch
def MailGrid(self,*args,**kwargs): mail_txt = Content('text/plain',emailbody) message = Mail( from_email=sendermail, to_emails=recivermail, subject=subject, html_content=htmlcontent ) message.add_content(mail_txt) if attach is not None: if os.path.isfile(attach): head, tail = os.path.split(attach) with open(attach, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() else: encoded = attach attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName(tail) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment SENDGRID_API_KEY = "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" sendgrid_client = sendgrid.SendGridAPIClient(SENDGRID_API_KEY ) response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers)
def sendgrid_sendmail(self, _apikey, _from, _to, _subject, _body, attachments=[]): file_name, data = attachments[0] sg = sendgrid.SendGridAPIClient(apikey=_apikey) from_email = Email(_from) subject = _subject to_email = Email(_to) content = Content("text/plain", _body) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.content = encoded attachment.type = "application/x-mobipocket-ebook" attachment.filename = file_name attachment.disposition = "attachment" attachment.content_id = "kindleear" mail = Mail(from_email, subject, to_email, content) mail.add_attachment(attachment) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: default_log.warn('Sendgrid succeed send mail : %s', file_name) else: default_log.warn('Sendgrid send mail failed, error code: %s', str(response.status_code)) return response.status_code
def send_simple_mail(subj='Sending with Twilio SendGrid is Fun'): message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject=subj, html_content= '<strong>and easy to do anywhere, even with Python</strong>') import os THIS_FOLDER = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(THIS_FOLDER, 'bumblebees-flowers.jpg') # file_path = 'bumblebees-flowers.jpg' with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/jpeg') attachment.file_name = FileName('bumblebees-flowers.jpg') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message)
def job(): prices = [] stars = [] titles = [] urlss = [] pages_to_scrape = 10 pages = [('http://books.toscrape.com/catalogue/page-{}.html').format(i) for i in range(1, pages_to_scrape + 1)] for item in pages: page = requests.get(item) soup = bs4(page.text, 'html.parser') for i in soup.findAll('h3'): titles.append(i.getText()) for j in soup.findAll('p', class_='price_color'): prices.append(j.getText()) for s in soup.findAll('p', class_='star-rating'): for k, v in s.attrs.items(): stars.append(v[1]) divs = soup.findAll('div', class_='image_container') for thumbs in divs: tgs = thumbs.find('img', class_='thumbnail') urls = 'http://books.toscrape.com/' + str(tgs['src']) newurls = urls.replace("../", "") urlss.append(newurls) data = {'Title': titles, 'Prices': prices, 'Stars': stars, "URLs": urlss} df = pd.DataFrame(data=data) df.index += 1 directory = os.path.dirname(os.path.realpath(__file__)) filename = "scrapedfile.csv" file_path = os.path.join(directory, 'csvfiles/', filename) df.to_csv(file_path) with open(file_path, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() message = Mail( from_email=FROM_EMAIL, to_emails=TO_EMAIL, subject='Your File is Ready', html_content='<strong>Attached is Your Scraped File</strong>') attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('text/csv') attachment.file_name = FileName('scraped.csv') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def send_mail_sendgrid(description, agenda: Agenda): c = Calendar() e = Event() e.name = 'Atendimento Aset Terapias' str_begin = '-'.join(reversed(agenda.date.split('/'))) str_begin = f'{str_begin} {agenda.time}' e.begin = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') + timedelta(hours=3)) e.end = (datetime.strptime(str_begin, '%Y-%m-%d %H:%M') + timedelta(hours=4)) e.attendees = [agenda.appointment.customer.email, agenda.therapist.email] e.description = description c.events.add(e) curdir = os.getcwd() with open(f'{curdir}{os.sep}go.ics', 'w') as f: f.writelines(c) with open( f'{curdir}{os.sep}apps{os.sep}agenda{os.sep}email_templates{os.sep}appointment-confirmation.html', encoding='utf-8') as templ: body = ''.join(templ.readlines()) body = body.replace('{{nome}}', agenda.appointment.customer.name) body = body.replace('{{nome_terapia}}', agenda.appointment.specialty) body = body.replace('{{nome_terapeuta}}', agenda.therapist.name) body = body.replace('{{data}}', agenda.date) body = body.replace('{{hora}}', agenda.time) body = body.replace('{{api}}', os.getenv("API_ENDPOINT")) body = body.replace('{{calendar}}', agenda.calendar.name) body = body.replace('{{therapist_mail}}', agenda.therapist.email) body = body.replace('{{date}}', agenda.date.replace('/', '-')) body = body.replace('{{hour}}', agenda.time) body = body.replace('{{text}}', agenda.appointment.text) message = Mail(from_email=os.getenv("EMAIL_SENDER"), to_emails=agenda.appointment.customer.email, subject='Aset Terapias : Confirmação de consulta', html_content=body) try: message.add_bcc(agenda.therapist.email) with open(f'{curdir}{os.sep}go.ics', 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_name = FileName('go.ics') attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Unique Content ID') message.attachment = attachment sg = SendGridAPIClient(api_key=os.getenv('EMAIL_TOKEN')) sg.send(message=message) except Exception as e: print('Erro no envio de e-mail') print(e)
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', **kwargs): """ Send an email with html content using sendgrid. To use this plugin: 0. include sendgrid subpackage as part of your Airflow installation, e.g., pip install airflow[sendgrid] 1. update [email] backend in airflow.cfg, i.e., [email] email_backend = airflow.contrib.utils.sendgrid.send_email 2. configure Sendgrid specific environment variables at all Airflow instances: SENDGRID_MAIL_FROM={your-mail-from} SENDGRID_API_KEY={your-sendgrid-api-key}. """ mail = Mail() mail.from_email = Email(os.environ.get('SENDGRID_MAIL_FROM')) mail.subject = subject # Add the recipient list of to emails. personalization = Personalization() to = get_email_address_list(to) for to_address in to: personalization.add_to(Email(to_address)) if cc: cc = get_email_address_list(cc) for cc_address in cc: personalization.add_cc(Email(cc_address)) if bcc: bcc = get_email_address_list(bcc) for bcc_address in bcc: personalization.add_bcc(Email(bcc_address)) # Add custom_args to personalization if present pers_custom_args = kwargs.get('personalization_custom_args', None) if isinstance(pers_custom_args, dict): for key in pers_custom_args.keys(): personalization.add_custom_arg(CustomArg(key, pers_custom_args[key])) mail.add_personalization(personalization) mail.add_content(Content('text/html', html_content)) categories = kwargs.get('categories', []) for cat in categories: mail.add_category(Category(cat)) # Add email attachment. for fname in files or []: basename = os.path.basename(fname) attachment = Attachment() with open(fname, "rb") as f: attachment.content = base64.b64encode(f.read()) attachment.type = mimetypes.guess_type(basename)[0] attachment.filename = basename attachment.disposition = "attachment" attachment.content_id = '<%s>' % basename mail.add_attachment(attachment) _post_sendgrid_mail(mail.get())
def email_thread(queue: Queue, API: str, TESTER: str, EMAIL: str): status = '' running = True while running: data = queue.get() if data.message_type == 1: status = status + data.task_name + ': ' + data.message + '\n' elif data.message_type == 2: status = status + 'Warning: ' + data.task_name + ': ' + data.message + '\n' elif data.message_type == 3: status = status + 'Error: ' + data.task_name + ': ' + data.message + '\n' elif data.message_type == 4: status = status + 'Error: Test Failed: ' + data.task_name + '\n' + \ str(data.exception[0]) + '\n' + str(data.exception[1] ) + '\n' + traceback.format_tb(data.exception[2])[0] running = False elif data.message_type == 0: status = status + 'Test from unit: ' + TESTER + \ ' has completed successfully, see results attached' running = False file_name = data.file_name print(data.task_name + ': ' + data.message) queue.task_done() print('sending email') zip_file = '{}.zip'.format(file_name) with ZipFile(zip_file, 'w') as zip: zip.write('{}.jpg'.format(file_name)) zip.write('{}_hist.png'.format(file_name)) zip.write('{}_hist.json'.format(file_name)) message = Mail(from_email=TESTER + '@example.com', to_emails=EMAIL, subject='Test Results for Tester: ' + TESTER + ' at time: x', html_content='<p>' + status + '<p>') with open(zip_file, 'rb') as f: data = f.read() f.close() encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/zip') attachment.file_name = FileName('{}.zip'.format(file_name)) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Test Results') message.attachment = attachment try: sg = SendGridAPIClient(API) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(type(e)) + ' ' + str(e)) # code for sending email print('finished sending email') print(status)
def create_attachment(file_path): new_attachment = Attachment() new_attachment.content = get_content(file_path) new_attachment.type = get_mime(file_path) new_attachment.filename = get_basename(file_path) new_attachment.disposition = 'attachment' new_attachment.content_id = '{} File'.format( get_extension(file_path).upper()) return new_attachment
def final_s(): directory = os.path.dirname(os.path.realpath(__file__)) filename2 = "results.csv" final_r = "virtual.csv" filename = "scrapedfile.csv" file_path = os.path.join(directory, 'clean/', filename) file_path3 = os.path.join(directory, 'clean/', final_r) file_path2 = os.path.join(directory, 'clean/', filename2) f = pd.read_csv(file_path) h = pd.read_csv(file_path2) df_merge_col = pd.merge(f, h, on='Match No') del df_merge_col['HomeTeam_y'] del df_merge_col['AwayTeam_y'] df_merge_col = df_merge_col.rename(columns={ 'HomeTeam_x': 'HomeTeam', 'AwayTeam_x': 'AwayTeam' }) df_merge_col.to_csv(file_path3, index=False) file_data = pd.read_csv(file_path3) dr = file_data.drop_duplicates(subset=['Match No'], keep='first') dr.to_csv(file_path3, index=False) insert() with open(file_path3, 'rb') as file: data_ = file.read() file.close() encoded = base64.b64encode(data_).decode() message = Mail( from_email=FROM_EMAIL, to_emails=TO_EMAIL, subject='Your File is Ready', html_content='<strong>Attached is Your Scraped File</strong>') attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('text/csv') x = datetime.datetime.now() w = x.strftime("%d_%b_%Y") filename = 'virtuals_' + str(w) + '.csv' attachment.file_name = FileName(filename) attachment.disposition = Disposition('attachment') attachment.content_id = ContentId('Example Content ID') message.attachment = attachment try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e) os.remove(file_path) print( 'combined the two csv files and created the final virtuals dataframe\nAnd then deleted the scrapedfile' )
def build_attachment2(): """Build attachment mock.""" attachment = Attachment() attachment.content = "BwdW" attachment.type = "image/png" attachment.filename = "banner.png" attachment.disposition = "inline" attachment.content_id = "Banner" return attachment
def build_attachment2(): """Build attachment mock.""" attachment = Attachment() attachment.content = "BwdW" attachment.type = "image/png" attachment.filename = "banner.png" attachment.disposition = "inline" attachment.content_id = "Banner" return attachment
def build_attachment(file_path, disposition="attachment", content_id="Ebook"): filename, file_type, content = file_info(file_path) attachment = Attachment() attachment.file_content = FileContent(content) attachment.file_type = FileType(file_type) attachment.file_name = FileName(filename) attachment.disposition = Disposition(disposition) attachment.content_id = ContentId(content_id) return attachment
def build_attachment1(): """Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md""" attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12") attachment.type = "application/pdf" attachment.filename = "balance_001.pdf" attachment.disposition = "attachment" attachment.content_id = "Balance Sheet" return attachment
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', **kwargs): """ Send an email with html content using sendgrid. To use this plugin: 0. include sendgrid subpackage as part of your Airflow installation, e.g., pip install airflow[sendgrid] 1. update [email] backend in airflow.cfg, i.e., [email] email_backend = airflow.contrib.utils.sendgrid.send_email 2. configure Sendgrid specific environment variables at all Airflow instances: SENDGRID_MAIL_FROM={your-mail-from} SENDGRID_API_KEY={your-sendgrid-api-key}. """ mail = Mail() mail.from_email = Email(os.environ.get('SENDGRID_MAIL_FROM')) mail.subject = subject # Add the recipient list of to emails. personalization = Personalization() to = get_email_address_list(to) for to_address in to: personalization.add_to(Email(to_address)) if cc: cc = get_email_address_list(cc) for cc_address in cc: personalization.add_cc(Email(cc_address)) if bcc: bcc = get_email_address_list(bcc) for bcc_address in bcc: personalization.add_bcc(Email(bcc_address)) mail.add_personalization(personalization) mail.add_content(Content('text/html', html_content)) # Add custom_args to personalization if present pers_custom_args = kwargs.get('personalization_custom_args', None) if isinstance(pers_custom_args, dict): for key in pers_custom_args.keys(): personalization.add_custom_arg(CustomArg(key, pers_custom_args[key])) # Add email attachment. for fname in files or []: basename = os.path.basename(fname) attachment = Attachment() with open(fname, "rb") as f: attachment.content = base64.b64encode(f.read()) attachment.type = mimetypes.guess_type(basename)[0] attachment.filename = basename attachment.disposition = "attachment" attachment.content_id = '<%s>' % basename mail.add_attachment(attachment) _post_sendgrid_mail(mail.get())
def build_attachment1(): """Build attachment mock. Make sure your content is base64 encoded before passing into attachment.content. Another example: https://github.com/sendgrid/sendgrid-python/blob/master/use_cases/attachment.md""" attachment = Attachment() attachment.content = ("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNl" "Y3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12") attachment.type = "application/pdf" attachment.filename = "balance_001.pdf" attachment.disposition = "attachment" attachment.content_id = "Balance Sheet" return attachment
def _create_attachment(cls, attachment: dict) -> Attachment: filename = attachment.get('filename', '') content = attachment.get('content', '') mail_attachment = Attachment() mail_attachment.disposition = 'attachment' mail_attachment.filename = filename mail_attachment.content_id = filename mail_attachment.type = guess_type(filename)[0] mail_attachment.content = content return mail_attachment
def sendgrid_sendmail(self, _apikey, _from, _to, _subject, _body, attachments=[]): file_name, data = attachments[0] sg = sendgrid.SendGridAPIClient(apikey=_apikey) from_email = Email(_from) subject = _subject to_email = Email(_to) content = Content("text/plain", _body) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.content = encoded attachment.type = "application/x-mobipocket-ebook" attachment.filename = file_name attachment.disposition = "attachment" attachment.content_id = "kindleear" mail = Mail(from_email, subject, to_email, content) mail.add_attachment(attachment) response = sg.client.mail.send.post(request_body=mail.get()) if response.status_code == 202: default_log.warn('Sendgrid succeed send mail : %s', file_name) else: default_log.warn('Sendgrid send mail failed, error code: %s', str(response.status_code)) return response.status_code
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', sandbox_mode=False, **kwargs): """ Send an email with html content using sendgrid. To use this plugin: 0. include sendgrid subpackage as part of your Airflow installation, e.g., pip install 'apache-airflow[sendgrid]' 1. update [email] backend in airflow.cfg, i.e., [email] email_backend = airflow.contrib.utils.sendgrid.send_email 2. configure Sendgrid specific environment variables at all Airflow instances: SENDGRID_MAIL_FROM={your-mail-from} SENDGRID_API_KEY={your-sendgrid-api-key}. """ if files is None: files = [] mail = Mail() from_email = kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM') from_name = kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER') mail.from_email = Email(from_email, from_name) mail.subject = subject mail.mail_settings = MailSettings() if sandbox_mode: mail.mail_settings.sandbox_mode = SandBoxMode(enable=True) # Add the recipient list of to emails. personalization = Personalization() to = get_email_address_list(to) for to_address in to: personalization.add_to(Email(to_address)) if cc: cc = get_email_address_list(cc) for cc_address in cc: personalization.add_cc(Email(cc_address)) if bcc: bcc = get_email_address_list(bcc) for bcc_address in bcc: personalization.add_bcc(Email(bcc_address)) # Add custom_args to personalization if present pers_custom_args = kwargs.get('personalization_custom_args', None) if isinstance(pers_custom_args, dict): for key in pers_custom_args.keys(): personalization.add_custom_arg(CustomArg(key, pers_custom_args[key])) mail.add_personalization(personalization) mail.add_content(Content('text/html', html_content)) categories = kwargs.get('categories', []) for cat in categories: mail.add_category(Category(cat)) # Add email attachment. for fname in files: basename = os.path.basename(fname) attachment = Attachment() attachment.type = mimetypes.guess_type(basename)[0] attachment.filename = basename attachment.disposition = "attachment" attachment.content_id = '<{0}>'.format(basename) with open(fname, "rb") as f: attachment.content = base64.b64encode(f.read()).decode('utf-8') mail.add_attachment(attachment) _post_sendgrid_mail(mail.get())
def _build_sg_mail(self, msg): mail = Mail() mail.from_email = Email(*self._parse_email_address(msg.from_email)) mail.subject = msg.subject personalization = Personalization() for addr in msg.to: personalization.add_to(Email(*self._parse_email_address(addr))) for addr in msg.cc: personalization.add_cc(Email(*self._parse_email_address(addr))) for addr in msg.bcc: personalization.add_bcc(Email(*self._parse_email_address(addr))) personalization.subject = msg.subject for k, v in msg.extra_headers.items(): if k.lower() == "reply-to": mail.reply_to = Email(v) else: personalization.add_header(Header(k, v)) if hasattr(msg, "template_id"): mail.template_id = msg.template_id if hasattr(msg, "substitutions"): for k, v in msg.substitutions.items(): personalization.add_substitution(Substitution(k, v)) # write through the ip_pool_name attribute if hasattr(msg, "ip_pool_name"): if not isinstance(msg.ip_pool_name, basestring): raise ValueError( "ip_pool_name must be a string, got: {}; " "see https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/" "index.html#-Request-Body-Parameters".format( type(msg.ip_pool_name))) if not 2 <= len(msg.ip_pool_name) <= 64: raise ValueError( "the number of characters of ip_pool_name must be min 2 and max 64, got: {}; " "see https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/" "index.html#-Request-Body-Parameters".format( len(msg.ip_pool_name))) mail.ip_pool_name = msg.ip_pool_name # write through the send_at attribute if hasattr(msg, "send_at"): if not isinstance(msg.send_at, int): raise ValueError( "send_at must be an integer, got: {}; " "see https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html#-Send-At".format( type(msg.send_at))) personalization.send_at = msg.send_at mail.add_personalization(personalization) if hasattr(msg, "reply_to") and msg.reply_to: if mail.reply_to: # If this code path is triggered, the reply_to on the sg mail was set in a header above reply_to = Email(*self._parse_email_address(msg.reply_to)) if reply_to.email != mail.reply_to.email or reply_to.name != mail.reply_to.name: raise ValueError("Sendgrid only allows 1 email in the reply-to field. " + "Reply-To header value != reply_to property value.") if not isinstance(msg.reply_to, basestring): if len(msg.reply_to) > 1: raise ValueError("Sendgrid only allows 1 email in the reply-to field") mail.reply_to = Email(*self._parse_email_address(msg.reply_to[0])) else: mail.reply_to = Email(*self._parse_email_address(msg.reply_to)) for attch in msg.attachments: attachment = Attachment() if isinstance(attch, MIMEBase): filename = attch.get_filename() if not filename: ext = mimetypes.guess_extension(attch.get_content_type()) filename = "part-{0}{1}".format(uuid.uuid4().hex, ext) attachment.filename = filename # todo: Read content if stream? attachment.content = attch.get_payload().replace("\n", "") attachment.type = attch.get_content_type() content_id = attch.get("Content-ID") if content_id: # Strip brackets since sendgrid's api adds them if content_id.startswith("<") and content_id.endswith(">"): content_id = content_id[1:-1] attachment.content_id = content_id attachment.disposition = "inline" else: filename, content, mimetype = attch attachment.filename = filename # Convert content from chars to bytes, in both Python 2 and 3. # todo: Read content if stream? if isinstance(content, str): content = content.encode('utf-8') attachment.content = base64.b64encode(content).decode() attachment.type = mimetype mail.add_attachment(attachment) msg.body = ' ' if msg.body == '' else msg.body if isinstance(msg, EmailMultiAlternatives): mail.add_content(Content("text/plain", msg.body)) for alt in msg.alternatives: if alt[1] == "text/html": mail.add_content(Content(alt[1], alt[0])) elif msg.content_subtype == "html": mail.add_content(Content("text/plain", " ")) mail.add_content(Content("text/html", msg.body)) else: mail.add_content(Content("text/plain", msg.body)) if hasattr(msg, "categories"): for cat in msg.categories: mail.add_category(Category(cat)) if hasattr(msg, "asm"): if "group_id" not in msg.asm: raise KeyError("group_id not found in asm") if "groups_to_display" in msg.asm: mail.asm = ASM(msg.asm["group_id"], msg.asm["groups_to_display"]) else: mail.asm = ASM(msg.asm["group_id"]) mail_settings = MailSettings() mail_settings.sandbox_mode = SandBoxMode(self.sandbox_mode) mail.mail_settings = mail_settings tracking_settings = TrackingSettings() tracking_settings.open_tracking = OpenTracking(self.track_email) mail.tracking_settings = tracking_settings return mail.get()
def test_kitchenSink(self): self.maxDiff = None """All settings set""" mail = Mail() mail.from_email = Email("*****@*****.**", "Example User") mail.subject = "Hello World from the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**", "Example User")) personalization.add_to(Email("*****@*****.**", "Example User")) personalization.add_cc(Email("*****@*****.**", "Example User")) personalization.add_cc(Email("*****@*****.**", "Example User")) personalization.add_bcc(Email("*****@*****.**")) personalization.add_bcc(Email("*****@*****.**")) personalization.subject = "Hello World from the Personalized SendGrid Python Library" personalization.add_header(Header("X-Test", "test")) personalization.add_header(Header("X-Mock", "true")) personalization.add_substitution( Substitution("%name%", "Example User")) personalization.add_substitution(Substitution("%city%", "Denver")) personalization.add_custom_arg(CustomArg("user_id", "343")) personalization.add_custom_arg(CustomArg("type", "marketing")) personalization.send_at = 1443636843 mail.add_personalization(personalization) personalization2 = Personalization() personalization2.add_to(Email("*****@*****.**", "Example User")) personalization2.add_to(Email("*****@*****.**", "Example User")) personalization2.add_cc(Email("*****@*****.**", "Example User")) personalization2.add_cc(Email("*****@*****.**", "Example User")) personalization2.add_bcc(Email("*****@*****.**")) personalization2.add_bcc(Email("*****@*****.**")) personalization2.subject = "Hello World from the Personalized SendGrid Python Library" personalization2.add_header(Header("X-Test", "test")) personalization2.add_header(Header("X-Mock", "true")) personalization2.add_substitution( Substitution("%name%", "Example User")) personalization2.add_substitution(Substitution("%city%", "Denver")) personalization2.add_custom_arg(CustomArg("user_id", "343")) personalization2.add_custom_arg(CustomArg("type", "marketing")) personalization2.send_at = 1443636843 mail.add_personalization(personalization2) mail.add_content(Content("text/plain", "some text here")) mail.add_content( Content( "text/html", "<html><body>some text here</body></html>")) attachment = Attachment() attachment.content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12" attachment.type = "application/pdf" attachment.filename = "balance_001.pdf" attachment.disposition = "attachment" attachment.content_id = "Balance Sheet" mail.add_attachment(attachment) attachment2 = Attachment() attachment2.content = "BwdW" attachment2.type = "image/png" attachment2.filename = "banner.png" attachment2.disposition = "inline" attachment2.content_id = "Banner" mail.add_attachment(attachment2) mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" mail.add_section( Section( "%section1%", "Substitution Text for Section 1")) mail.add_section( Section( "%section2%", "Substitution Text for Section 2")) mail.add_header(Header("X-Test1", "test1")) mail.add_header(Header("X-Test3", "test2")) mail.add_header({"X-Test4": "test4"}) mail.add_category(Category("May")) mail.add_category(Category("2016")) mail.add_custom_arg(CustomArg("campaign", "welcome")) mail.add_custom_arg(CustomArg("weekday", "morning")) mail.send_at = 1443636842 mail.batch_id = "sendgrid_batch_id" mail.asm = ASM(99, [4, 5, 6, 7, 8]) mail.ip_pool_name = "24" mail_settings = MailSettings() mail_settings.bcc_settings = BCCSettings( True, Email("*****@*****.**")) mail_settings.bypass_list_management = BypassListManagement(True) mail_settings.footer_settings = FooterSettings( True, "Footer Text", "<html><body>Footer Text</body></html>") mail_settings.sandbox_mode = SandBoxMode(True) mail_settings.spam_check = SpamCheck( True, 1, "https://spamcatcher.sendgrid.com") mail.mail_settings = mail_settings tracking_settings = TrackingSettings() tracking_settings.click_tracking = ClickTracking( True, True) tracking_settings.open_tracking = OpenTracking( True, "Optional tag to replace with the open image in the body of the message") tracking_settings.subscription_tracking = SubscriptionTracking( True, "text to insert into the text/plain portion of the message", "<html><body>html to insert into the text/html portion of the message</body></html>", "Optional tag to replace with the open image in the body of the message") tracking_settings.ganalytics = Ganalytics( True, "some source", "some medium", "some term", "some content", "some campaign") mail.tracking_settings = tracking_settings mail.reply_to = Email("*****@*****.**") expected_result = { "asm": { "group_id": 99, "groups_to_display": [4, 5, 6, 7, 8] }, "attachments": [ { "content": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3" "RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", "content_id": "Balance Sheet", "disposition": "attachment", "filename": "balance_001.pdf", "type": "application/pdf" }, { "content": "BwdW", "content_id": "Banner", "disposition": "inline", "filename": "banner.png", "type": "image/png" } ], "batch_id": "sendgrid_batch_id", "categories": [ "May", "2016" ], "content": [ { "type": "text/plain", "value": "some text here" }, { "type": "text/html", "value": "<html><body>some text here</body></html>" } ], "custom_args": { "campaign": "welcome", "weekday": "morning" }, "from": { "email": "*****@*****.**", "name": "Example User" }, "headers": { "X-Test1": "test1", "X-Test3": "test2", "X-Test4": "test4" }, "ip_pool_name": "24", "mail_settings": { "bcc": { "email": "*****@*****.**", "enable": True }, "bypass_list_management": { "enable": True }, "footer": { "enable": True, "html": "<html><body>Footer Text</body></html>", "text": "Footer Text" }, "sandbox_mode": { "enable": True }, "spam_check": { "enable": True, "post_to_url": "https://spamcatcher.sendgrid.com", "threshold": 1 } }, "personalizations": [ { "bcc": [ { "email": "*****@*****.**" }, { "email": "*****@*****.**" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ], "custom_args": { "type": "marketing", "user_id": "343" }, "headers": { "X-Mock": "true", "X-Test": "test" }, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid " "Python Library", "substitutions": { "%city%": "Denver", "%name%": "Example User" }, "to": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ] }, { "bcc": [ { "email": "*****@*****.**" }, { "email": "*****@*****.**" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ], "custom_args": { "type": "marketing", "user_id": "343" }, "headers": { "X-Mock": "true", "X-Test": "test" }, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid " "Python Library", "substitutions": { "%city%": "Denver", "%name%": "Example User" }, "to": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ] } ], "reply_to": { "email": "*****@*****.**" }, "sections": { "%section1%": "Substitution Text for Section 1", "%section2%": "Substitution Text for Section 2" }, "send_at": 1443636842, "subject": "Hello World from the SendGrid Python Library", "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932", "tracking_settings": { "click_tracking": { "enable": True, "enable_text": True }, "ganalytics": { "enable": True, "utm_campaign": "some campaign", "utm_content": "some content", "utm_medium": "some medium", "utm_source": "some source", "utm_term": "some term" }, "open_tracking": { "enable": True, "substitution_tag": "Optional tag to replace with the " "open image in the body of the message" }, "subscription_tracking": { "enable": True, "html": "<html><body>html to insert into the text/html " "portion of the message</body></html>", "substitution_tag": "Optional tag to replace with the open" " image in the body of the message", "text": "text to insert into the text/plain portion of" " the message" } } } self.assertEqual( json.dumps(mail.get(), sort_keys=True), json.dumps(expected_result, sort_keys=True) )