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 build_message(from_email: str, to_emails: tuple, subject: str, html_content: str, file_name: str): message = Mail( from_email=from_email, to_emails=to_emails, subject=subject, html_content=html_content ) if os.path.isfile(file_name): with open(file=file_name, mode='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/html') attachment.file_name = FileName('Music_Recommendations.html') attachment.disposition = Disposition('attachment') message.attachment = attachment return message
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 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 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 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 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 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 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(self, request): contents = self.contents.read().decode('utf-8') subscribers = Subscriber.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject=self.subject, html_content=contents + ( '<br><center>If you no longer wish to receive our newsletters, you can ' \ '<a href="{}/?email={}&conf_num={}">unsubscribe</a></center>.').format( request.build_absolute_uri('/delete/'), sub.email, sub.conf_num)) with open(self.attachment.path, 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment(FileContent(encoded_file), FileName(self.attachment.path), FileType('application/pdf'), Disposition('attachment')) message.attachment = attachedFile sg.send(message)
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 send(self): message = Mail( from_email="*****@*****.**", to_emails=NOTIFICATION_RECIPIENTS, subject="TSLA Model Prediction from Tradium", html_content="<strong>predictions from Tradium</strong>", ) with open(get_abs_path(__file__, "../charts/tsla-prediction.png"), "rb") as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment( FileContent(encoded_file), FileName("chart.png"), FileType("application/png"), Disposition("attachment"), ) message.attachment = attachedFile try: sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) print(f"Email sent status code: {response.status_code}") print(f"Email sent response body: {response.body}") except Exception as e: print(f"Printing exception: ", e)
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 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 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 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 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 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 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 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(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 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(): 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(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 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 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='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)