def _build_sg_mail(self, email): mail = Mail() from_name, from_email = rfc822.parseaddr(email.from_email) # Python sendgrid client should improve # sendgrid/helpers/mail/mail.py:164 if not from_name: from_name = None mail.set_from(Email(from_email, from_name)) mail.set_subject(email.subject) personalization = Personalization() for e in email.to: personalization.add_to(Email(e)) for e in email.cc: personalization.add_cc(Email(e)) for e in email.bcc: personalization.add_bcc(Email(e)) personalization.set_subject(email.subject) mail.add_content(Content("text/plain", email.body)) if isinstance(email, EmailMultiAlternatives): for alt in email.alternatives: if alt[1] == "text/html": mail.add_content(Content(alt[1], alt[0])) elif email.content_subtype == "html": mail.contents = [] mail.add_content(Content("text/plain", ' ')) mail.add_content(Content("text/html", email.body)) if hasattr(email, 'categories'): for c in email.categories: mail.add_category(Category(c)) if hasattr(email, 'template_id'): mail.set_template_id(email.template_id) if hasattr(email, 'substitutions'): for k, v in email.substitutions.items(): personalization.add_substitution(Substitution(k, v)) for k, v in email.extra_headers.items(): mail.add_header({k: v}) for attachment in email.attachments: if isinstance(attachment, MIMEBase): attach = Attachment() attach.set_filename(attachment.get_filename()) attach.set_content(base64.b64encode(attachment.get_payload())) mail.add_attachment(attach) elif isinstance(attachment, tuple): attach = Attachment() attach.set_filename(attachment[0]) base64_attachment = base64.b64encode(attachment[1]) if sys.version_info >= (3, ): attach.set_content(str(base64_attachment, 'utf-8')) else: attach.set_content(base64_attachment) attach.set_type(attachment[2]) mail.add_attachment(attach) mail.add_personalization(personalization) return mail.get()
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 digicam_sender(file_path: str, user_email: str, is_for_card: bool): """Sends the images to the users email""" # Sending is optional. if config.sendgrid_key is None: return html_content = """Hello! Attached are your images from the Digicam Print Channel. We hope you enjoy, and thank you for using our service!""" if is_for_card: html_content += f""" It looks like you ordered a business card. Did you know you can share these publicly via Digicard? If you're interested, visit https://card.wiilink24.com. Your order ID to link is {current_order.order_id}. Do not share this order ID with anyone else, or they will be able to use your card. """ html_content += """ The WiiLink24 Team""" msg = Mail( from_email="*****@*****.**", to_emails=user_email, subject="Here is your order!", html_content=html_content, ) with open(file_path, "rb") as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() if is_for_card: msg.attachment = Attachment( FileContent(encoded_file), FileName("business_card.jpeg"), FileType("application/jpeg"), Disposition("attachment"), ) else: msg.attachment = Attachment( FileContent(encoded_file), FileName("images.zip"), FileType("application/zip"), Disposition("attachment"), ) sg = SendGridAPIClient(config.sendgrid_key) sg.send(msg)
def test_attachment(self): from sendgrid.helpers.mail import (FileContent, FileType, FileName, Disposition, ContentId) a1 = Attachment(FileContent('Base64EncodedString'), FileName('example.pdf'), FileType('application/pdf'), Disposition('attachment'), ContentId('123')) a2 = Attachment('Base64EncodedString', 'example.pdf', 'application/pdf', 'attachment', '123') self.assertEqual(a1.file_content.get(), a2.file_content.get()) self.assertEqual(a1.file_name.get(), a2.file_name.get()) self.assertEqual(a1.file_type.get(), a2.file_type.get()) self.assertEqual(a1.disposition.get(), a2.disposition.get()) self.assertEqual(a1.content_id.get(), a2.content_id.get())
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 sendMail(file_path, timesec, to_mail): message = Mail( from_email='*****@*****.**', to_emails=to_mail, subject='IGuard: Обнаружено Нарушение', html_content="<strong>Обнаружено нарушение в {}</strong>".format( time.strftime('%H:%M:%S, %d.%m.%Y', time.localtime(timesec)))) 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('image/jpg') attachment.file_name = FileName('ImageIGuard.jpg') message.attachment = attachment try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e)
def email_with_html_attachment(from_email: str, to_email: str, subject: str, body: str, filename: str, file_path: str): import base64 from apis import authentication from sendgrid.helpers.mail import (Mail, Attachment, FileContent, FileName, FileType, Disposition) from sendgrid import SendGridAPIClient message = Mail(from_email=from_email, to_emails=to_email, subject=subject, html_content=body) 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('text/html') attachment.file_name = FileName(filename) attachment.disposition = Disposition('attachment') message.attachment = attachment try: sendgrid_client = SendGridAPIClient( authentication.get_token('https://www.apitutor.org/sendgrid/key')) sendgrid_client.send(message) return True except: 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 send_email(self): """Send email with transcription attached""" import base64 from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import (Mail, Attachment, Email, FileContent, FileName, FileType) text_file = "transcription.txt" mail = Mail( from_email=Email('*****@*****.**', "Chi from Damaris"), to_emails=self.email, subject="Your transcription from Damaris 🔥", plain_text_content="Thank you for using Damaris. Please find \ attached your transcribed file.") with open(text_file, 'rb') as f: data = f.read() encoded_text_file = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded_text_file) attachment.file_type = FileType("text/plain") attachment.file_name = FileName("transcription.txt") mail.attachment = attachment try: sg = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) sg.send(mail) log.info('Email sent successfully!') except Exception as e: log.error("Could not send email {}".format(e))
def generate_attachment(filepath, filetype="application/pdf", filename=None): """given a filepath, generate an attachment object for SendGrid by reading it in and encoding in base64. Parameters ========== filepath: the file path to attach on the server. filetype: MIME content type (defaults to application/pdf) filename: a filename for the attachment (defaults to basename provided) """ if not os.path.exists(filepath): return # Read in the attachment, base64 encode it with open(filepath, "rb") as filey: data = filey.read() # The filename can be provided, or the basename of actual file if not filename: filename = os.path.basename(filepath) encoded = base64.b64encode(data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType(filetype) attachment.file_name = FileName(filename) attachment.disposition = Disposition("attachment") return attachment
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 create_ticket_message(ticket): event = ticket.article.event tmpl = loader.get_template('events/email/ticket_message.md') subject = 'Entrada para {}'.format(event.name) body = tmpl.render({ 'ticket': ticket, 'article': ticket.article, 'category': ticket.article.category, 'event': event, }) mail = Mail(from_email=Email(settings.CONTACT_EMAIL, settings.ASSOCIATION_NAME), subject=subject, to_email=Email(ticket.customer_email), content=Content('text/html', as_markdown(body))) attachment = Attachment() pdf_filename = ticket.as_pdf() with open(pdf_filename, 'rb') as f: data = f.read() attachment.content = base64.b64encode(data).decode() attachment.type = 'application/pdf' attachment.filename = 'ticket.pdf' attachment.disposition = 'attachment' mail.add_attachment(attachment) return mail
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_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 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 send_email(filename): import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, Attachment, FileContent, FileName, FileType, Disposition to_emails = [('*****@*****.**', 'Suyoj Man Tamrakar'), ('*****@*****.**', 'Sanjay Man Tamrakar')] with open(filename, 'rb') as fd: encoded = base64.b64encode(fd.read()).decode() attachment = Attachment(FileContent(encoded), FileName(filename), FileType('text/csv'), Disposition('attachment')) print('Sendinggggggg') message = Mail( from_email=('*****@*****.**', 'Suyoj Man Tamrakar'), to_emails=to_emails, subject='Sentiment Survey Past Results', html_content= "<h2>These are the following details of the Sentiment Survey Past Results.</h2>" " <h2>STAY HOME STAY SAFE </h2> ") message.attachment = attachment try: sendgrid_client = SendGridAPIClient('') response = sendgrid_client.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print('Errrrorrrrrrrrrr') print(e) return "Done"
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 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 digicam_sender(file, toemail, password): """Sends the images to the users email""" msg = Mail( from_email="*****@*****.**", to_emails=toemail, subject="Here is your photo!", html_content=f"The photo is in attachments! Enjoy! The password is {password}", ) with open(file, "rb") as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() msg.attachment = Attachment( FileContent(encoded_file), FileName("images.zip"), FileType("application/zip"), Disposition("attachment"), ) sg = SendGridAPIClient(config.sendgrid_key) response = sg.send(msg) print(response.status_code)
def posiljanje( recipient="*****@*****.**", subject=f"Mass HR dokumentacija {datum}", message="Sporočilo je bilo avtomatizirano s pomočjo Pythona.\nSestavil, uredil in poslal: Erik Jerman\n", file_path=f'{path}/csv_in_xlsx_datoteke_HR/{datum}.xlsx'): print(f"Sending {subject}") to_emails = [('*****@*****.**'), (recipient)] message = Mail(from_email='*****@*****.**', to_emails=to_emails, is_multiple=True, subject=subject, html_content=message) try: with open(file_path, 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment(FileContent(encoded_file), FileName(f'{datum}.xlsx'), FileType('text/xlsx'), Disposition('attachment')) message.attachment = attachedFile except FileNotFoundError: print("Datoteka ne obstaja") sg = SendGridAPIClient('ENTER_YOUR_API_KEY_HERE') response = sg.send(message) print(response.status_code, response.body, response.headers)
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_task_sendgrid(payload, headers, smtp_config): try: message = Mail(from_email=From(payload['from'], payload['fromname']), to_emails=payload['to'], subject=payload['subject'], html_content=payload["html"]) if payload['attachments'] is not None: for attachment in payload['attachments']: with open(attachment, 'rb') as f: file_data = f.read() f.close() encoded = base64.b64encode(file_data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName(payload['to']) attachment.disposition = Disposition('attachment') message.add_attachment(attachment) sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key']) logging.info('Sending an email regarding {} on behalf of {}'.format( payload["subject"], payload["from"])) sendgrid_client.send(message) logging.info('Email sent successfully') except urllib.error.HTTPError as e: if e.code == 429: logging.warning("Sendgrid quota has exceeded") send_email_task_smtp.delay(payload=payload, headers=None, smtp_config=smtp_config) elif e.code == 554: empty_attachments_send(sendgrid_client, message) else: logging.exception( "The following error has occurred with sendgrid-{}".format( str(e)))
def send(): receiver = request.form['email-input'] pdf_path = './' + request.form['pdf'][1:] pdf_filename = pdf_path.split('static/media/')[-1] print(pdf_path) print(pdf_filename) message = Mail( from_email='*****@*****.**', to_emails=receiver, subject='Scribe: Your notes.', html_content= "<p>Scribe has sent you notes! View the attached PDF for audio transcription and visual aides.</p><br><br><p>Class Scribe</p>" ) with open(pdf_path, 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attached_file = Attachment(FileContent(encoded_file), FileName(pdf_filename), FileType('application/pdf'), Disposition('attachment')) message.attachment = attached_file try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) except Exception as e: print(e) flash('Email sent! You may upload another video file now.') return redirect(url_for('upload'))
def send_email_notification(user, from_email, to_email, subject, body, attachment_url=None): if to_email: message = Mail( from_email=from_email, to_emails=to_email, subject=subject, html_content=body ) if attachment_url is not None: try: document = requests.get(attachment_url).content document = base64.b64encode(document) message.attachment = Attachment(FileContent(document.decode()), FileName('account-summary.pdf'), FileType('application/pdf'), Disposition('attachment') ) except Exception as e: raise e try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) status = True except Exception as e: logger.error("Email not sent !", exc_info=True) status = False
def update(self, instance, validated_data): user = self.context['request'].user mail_subject = 'Покупка пакета' message = render_to_string('liqpay.html', { 'pocket': validated_data['user_pocket'], }) data = { 'to_emails': [ user.email, ], 'subject': mail_subject, 'html_content': message } pdfkit.from_string('TEST', 'smart_lead_pocket_paid.pdf') from_email = settings.DEFAULT_FROM_EMAIL message = Mail( from_email=from_email, **data, ) attachment = Attachment() with open('smart_lead_pocket_paid.pdf', 'rb') as f: attachment.file_content = base64.b64encode( f.read()).decode('utf-8') attachment.file_name = 'smart_lead_pocket_paid.pdf' message.add_attachment(attachment) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) sg.send(message) # send_email_task.delay(**data) return super().update(instance, validated_data)
def send_invoice_via_email(self, email): print("Sending email to {0}...".format(email)) message = Mail( from_email='*****@*****.**', to_emails=email, subject='New Order - Azen Store', html_content= '<strong>Your order has been received. Thanks for your purchase.</strong>' ) with open(os.path.join(settings.BASE_DIR, "invoice.pdf"), 'rb') as f: file_data = f.read() f.close() encoded_file = base64.b64encode(file_data).decode() attachedFile = Attachment(FileContent(encoded_file), FileName('attachment.pdf'), FileType('application/pdf'), Disposition('attachment')) message.attachment = attachedFile sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) print(response.status_code, response.body, response.headers)
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 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 add_attachment(self, data, file_name, file_type): encoded_file = base64.b64encode(data).decode() attached_file = Attachment(FileContent(encoded_file), FileName(file_name), FileType(file_type), Disposition('attachment')) self._message.attachment = attached_file
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)