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(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_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 send_email(subject="[Daily Briefing] This is a test", html="<p>Hello World</p>"): client = SendGridAPIClient(SENDGRID_API_KEY) #> <class 'sendgrid.sendgrid.SendGridAPIClient> print("CLIENT:", type(client)) print("SUBJECT:", subject) #print("HTML:", html) message = Mail( from_email=MY_EMAIL, to_emails=MY_EMAIL, subject=subject, html_content=html, ) with open('stock_info.xlsx', 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attached_file = Attachment( FileContent(encoded_file), FileName('stock_info.xlsx'), FileType('application/xlsx') #Disposition('attatchment') ) message.attachment = attached_file try: response = client.send(message) print("RESPONSE:", type(response)) #> <class 'python_http_client.client.Response'> print(response.status_code) #> 202 indicates SUCCESS return response except Exception as e: print("OOPS", e.message) return None
def sendMailWithPdf(email): #mailMsg = '{ # "subject": "subject", # "to": "*****@*****.**", # "from": "*****@*****.**", # "text": "Text", # "html": "", # "filename": "stats.xlsx", # "contentId": "stats" #}' #mailMsgJson = json.loads(mailMsg) message = Mail() message.to = To(email.data['to']) message.subject = Subject(email.data['subject'], p=0) message.from_email = From(email.data['from'], 'My Team Manager') message.template_id = TemplateId(email.data['templateId']) message.attachment = Attachment(FileContent(email.data['pdf']), FileName(email.data['filename']), FileType('application/pdf'), Disposition('attachment'), ContentId('Content ID 1')) message.content = Content(MimeType.text, email.data['text']) message.content = Content(MimeType.html, email.data['html']) sg = SendGridAPIClient(mailApiKey) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers)
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_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 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, 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 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 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, template, to_email, from_email, attachment, *args): if not (settings.ENV == "production"): if '*****@*****.**' in to_email: setting = Setting.objects.filter(key='tester_email').first() if setting and len(setting.value) > 0: to_email = [setting.value] else: to_email = [] if to_email and [email for email in to_email if len(email) > 0 ]: # TODO : regex validation on email os_path = 'services.email.templates.' + template module = importlib.import_module(os_path) message = getattr(module, 'message')(args) mail = Mail(from_email=from_email, to_emails=to_email, subject=subject, html_content=message) if attachment: mail.attachment = attachment try: sg = SendGridAPIClient(settings.CORE_SENDGRID_API_KEY) response = sg.send(mail) print(response.status_code) print(response.body) print(response.headers) return response except Exception as e: print("Error: ", e) import traceback tb = traceback.format_exc() print("trace:", tb)
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_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 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(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 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_email_update(test_mode, overall_total_positive, sendgrid_api_key): from_email = settings.from_email to_email = settings.to_email subject_prefix = settings.subject_prefix subject = subject_prefix + str(overall_total_positive) if test_mode: subject = "TEST MODE: " + subject html_content = 'See <a href=\"' + settings.url + '\">complete dashboard</a> for more information.' message = Mail(from_email=from_email, to_emails=to_email, subject=subject, html_content=html_content) with open('screenshot.png', 'rb') as f: data = f.read() f.close() encoded_file = base64.b64encode(data).decode() attachedFile = Attachment(FileContent(encoded_file), FileName('screenshot.png'), FileType('image/png'), Disposition('attachment')) message.attachment = attachedFile try: sg = SendGridAPIClient(sendgrid_api_key) sg.send(message) except Exception as e: print(e)
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(): 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(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 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(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 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 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(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_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(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 test_kitchen_sink(self): from sendgrid.helpers.mail import ( Mail, From, To, Cc, Bcc, Subject, Substitution, Header, CustomArg, SendAt, Content, MimeType, Attachment, FileName, FileContent, FileType, Disposition, ContentId, TemplateId, Section, ReplyTo, Category, BatchId, Asm, GroupId, GroupsToDisplay, IpPoolName, MailSettings, BccSettings, BccSettingsEmail, BypassListManagement, FooterSettings, FooterText, FooterHtml, SandBoxMode, SpamCheck, SpamThreshold, SpamUrl, TrackingSettings, ClickTracking, SubscriptionTracking, SubscriptionText, SubscriptionHtml, SubscriptionSubstitutionTag, OpenTracking, OpenTrackingSubstitutionTag, Ganalytics, UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign) self.maxDiff = None message = Mail() # Define Personalizations message.to = To('*****@*****.**', 'Example User1', p=0) message.to = [ To('*****@*****.**', 'Example User2', p=0), To('*****@*****.**', 'Example User3', p=0) ] message.cc = Cc('*****@*****.**', 'Example User4', p=0) message.cc = [ Cc('*****@*****.**', 'Example User5', p=0), Cc('*****@*****.**', 'Example User6', p=0) ] message.bcc = Bcc('*****@*****.**', 'Example User7', p=0) message.bcc = [ Bcc('*****@*****.**', 'Example User8', p=0), Bcc('*****@*****.**', 'Example User9', p=0) ] message.subject = Subject('Sending with SendGrid is Fun 0', p=0) message.header = Header('X-Test1', 'Test1', p=0) message.header = Header('X-Test2', 'Test2', p=0) message.header = [ Header('X-Test3', 'Test3', p=0), Header('X-Test4', 'Test4', p=0) ] message.substitution = Substitution('%name1%', 'Example Name 1', p=0) message.substitution = Substitution('%city1%', 'Example City 1', p=0) message.substitution = [ Substitution('%name2%', 'Example Name 2', p=0), Substitution('%city2%', 'Example City 2', p=0) ] message.custom_arg = CustomArg('marketing1', 'true', p=0) message.custom_arg = CustomArg('transactional1', 'false', p=0) message.custom_arg = [ CustomArg('marketing2', 'false', p=0), CustomArg('transactional2', 'true', p=0) ] message.send_at = SendAt(1461775051, p=0) message.to = To('*****@*****.**', 'Example User10', p=1) message.to = [ To('*****@*****.**', 'Example User11', p=1), To('*****@*****.**', 'Example User12', p=1) ] message.cc = Cc('*****@*****.**', 'Example User13', p=1) message.cc = [ Cc('*****@*****.**', 'Example User14', p=1), Cc('*****@*****.**', 'Example User15', p=1) ] message.bcc = Bcc('*****@*****.**', 'Example User16', p=1) message.bcc = [ Bcc('*****@*****.**', 'Example User17', p=1), Bcc('*****@*****.**', 'Example User18', p=1) ] message.header = Header('X-Test5', 'Test5', p=1) message.header = Header('X-Test6', 'Test6', p=1) message.header = [ Header('X-Test7', 'Test7', p=1), Header('X-Test8', 'Test8', p=1) ] message.substitution = Substitution('%name3%', 'Example Name 3', p=1) message.substitution = Substitution('%city3%', 'Example City 3', p=1) message.substitution = [ Substitution('%name4%', 'Example Name 4', p=1), Substitution('%city4%', 'Example City 4', p=1) ] message.custom_arg = CustomArg('marketing3', 'true', p=1) message.custom_arg = CustomArg('transactional3', 'false', p=1) message.custom_arg = [ CustomArg('marketing4', 'false', p=1), CustomArg('transactional4', 'true', p=1) ] message.send_at = SendAt(1461775052, p=1) message.subject = Subject('Sending with SendGrid is Fun 1', p=1) # The values below this comment are global to entire message message.from_email = From('*****@*****.**', 'DX') message.reply_to = ReplyTo('*****@*****.**', 'DX Reply') message.subject = Subject('Sending with SendGrid is Fun 2') message.content = Content( MimeType.text, 'and easy to do anywhere, even with Python') message.content = Content( MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>') message.content = [ Content('text/calendar', 'Party Time!!'), Content('text/custom', 'Party Time 2!!') ] message.attachment = Attachment( FileContent('base64 encoded content 1'), FileName('balance_001.pdf'), FileType('application/pdf'), Disposition('attachment'), ContentId('Content ID 1')) message.attachment = [ Attachment( FileContent('base64 encoded content 2'), FileName('banner.png'), FileType('image/png'), Disposition('inline'), ContentId('Content ID 2')), Attachment( FileContent('base64 encoded content 3'), FileName('banner2.png'), FileType('image/png'), Disposition('inline'), ContentId('Content ID 3')) ] message.template_id = TemplateId( '13b8f94f-bcae-4ec6-b752-70d6cb59f932') message.section = Section( '%section1%', 'Substitution for Section 1 Tag') message.section = [ Section('%section2%', 'Substitution for Section 2 Tag'), Section('%section3%', 'Substitution for Section 3 Tag') ] message.header = Header('X-Test9', 'Test9') message.header = Header('X-Test10', 'Test10') message.header = [ Header('X-Test11', 'Test11'), Header('X-Test12', 'Test12') ] message.category = Category('Category 1') message.category = Category('Category 2') message.category = [ Category('Category 1'), Category('Category 2') ] message.custom_arg = CustomArg('marketing5', 'false') message.custom_arg = CustomArg('transactional5', 'true') message.custom_arg = [ CustomArg('marketing6', 'true'), CustomArg('transactional6', 'false') ] message.send_at = SendAt(1461775053) message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi") message.asm = Asm(GroupId(1), GroupsToDisplay([1, 2, 3, 4])) message.ip_pool_name = IpPoolName("IP Pool Name") mail_settings = MailSettings() mail_settings.bcc_settings = BccSettings( False, BccSettingsEmail("*****@*****.**")) mail_settings.bypass_list_management = BypassListManagement(False) mail_settings.footer_settings = FooterSettings( True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>")) mail_settings.sandbox_mode = SandBoxMode(True) mail_settings.spam_check = SpamCheck( True, SpamThreshold(5), SpamUrl("https://example.com")) message.mail_settings = mail_settings tracking_settings = TrackingSettings() tracking_settings.click_tracking = ClickTracking(True, False) tracking_settings.open_tracking = OpenTracking( True, OpenTrackingSubstitutionTag("open_tracking")) tracking_settings.subscription_tracking = SubscriptionTracking( True, SubscriptionText("Goodbye"), SubscriptionHtml("<strong>Goodbye!</strong>"), SubscriptionSubstitutionTag("unsubscribe")) tracking_settings.ganalytics = Ganalytics( True, UtmSource("utm_source"), UtmMedium("utm_medium"), UtmTerm("utm_term"), UtmContent("utm_content"), UtmCampaign("utm_campaign")) message.tracking_settings = tracking_settings self.assertEqual( message.get(), json.loads(r'''{ "asm": { "group_id": 1, "groups_to_display": [ 1, 2, 3, 4 ] }, "attachments": [ { "content": "base64 encoded content 3", "content_id": "Content ID 3", "disposition": "inline", "filename": "banner2.png", "type": "image/png" }, { "content": "base64 encoded content 2", "content_id": "Content ID 2", "disposition": "inline", "filename": "banner.png", "type": "image/png" }, { "content": "base64 encoded content 1", "content_id": "Content ID 1", "disposition": "attachment", "filename": "balance_001.pdf", "type": "application/pdf" } ], "batch_id": "HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi", "categories": [ "Category 2", "Category 1", "Category 2", "Category 1" ], "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" }, { "type": "text/calendar", "value": "Party Time!!" }, { "type": "text/custom", "value": "Party Time 2!!" } ], "custom_args": { "marketing5": "false", "marketing6": "true", "transactional5": "true", "transactional6": "false" }, "from": { "email": "*****@*****.**", "name": "DX" }, "headers": { "X-Test10": "Test10", "X-Test11": "Test11", "X-Test12": "Test12", "X-Test9": "Test9" }, "ip_pool_name": "IP Pool Name", "mail_settings": { "bcc": { "email": "*****@*****.**", "enable": false }, "bypass_list_management": { "enable": false }, "footer": { "enable": true, "html": "<string>w00t!<strong>", "text": "w00t" }, "sandbox_mode": { "enable": true }, "spam_check": { "enable": true, "post_to_url": "https://example.com", "threshold": 5 } }, "personalizations": [ { "bcc": [ { "email": "*****@*****.**", "name": "Example User7" }, { "email": "*****@*****.**", "name": "Example User8" }, { "email": "*****@*****.**", "name": "Example User9" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User4" }, { "email": "*****@*****.**", "name": "Example User5" }, { "email": "*****@*****.**", "name": "Example User6" } ], "custom_args": { "marketing1": "true", "marketing2": "false", "transactional1": "false", "transactional2": "true" }, "headers": { "X-Test1": "Test1", "X-Test2": "Test2", "X-Test3": "Test3", "X-Test4": "Test4" }, "send_at": 1461775051, "subject": "Sending with SendGrid is Fun 0", "substitutions": { "%city1%": "Example City 1", "%city2%": "Example City 2", "%name1%": "Example Name 1", "%name2%": "Example Name 2" }, "to": [ { "email": "*****@*****.**", "name": "Example User1" }, { "email": "*****@*****.**", "name": "Example User2" }, { "email": "*****@*****.**", "name": "Example User3" } ] }, { "bcc": [ { "email": "*****@*****.**", "name": "Example User16" }, { "email": "*****@*****.**", "name": "Example User17" }, { "email": "*****@*****.**", "name": "Example User18" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User13" }, { "email": "*****@*****.**", "name": "Example User14" }, { "email": "*****@*****.**", "name": "Example User15" } ], "custom_args": { "marketing3": "true", "marketing4": "false", "transactional3": "false", "transactional4": "true" }, "headers": { "X-Test5": "Test5", "X-Test6": "Test6", "X-Test7": "Test7", "X-Test8": "Test8" }, "send_at": 1461775052, "subject": "Sending with SendGrid is Fun 1", "substitutions": { "%city3%": "Example City 3", "%city4%": "Example City 4", "%name3%": "Example Name 3", "%name4%": "Example Name 4" }, "to": [ { "email": "*****@*****.**", "name": "Example User10" }, { "email": "*****@*****.**", "name": "Example User11" }, { "email": "*****@*****.**", "name": "Example User12" } ] } ], "reply_to": { "email": "*****@*****.**", "name": "DX Reply" }, "sections": { "%section1%": "Substitution for Section 1 Tag", "%section2%": "Substitution for Section 2 Tag", "%section3%": "Substitution for Section 3 Tag" }, "send_at": 1461775053, "subject": "Sending with SendGrid is Fun 2", "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932", "tracking_settings": { "click_tracking": { "enable": true, "enable_text": false }, "ganalytics": { "enable": true, "utm_campaign": "utm_campaign", "utm_content": "utm_content", "utm_medium": "utm_medium", "utm_source": "utm_source", "utm_term": "utm_term" }, "open_tracking": { "enable": true, "substitution_tag": "open_tracking" }, "subscription_tracking": { "enable": true, "html": "<strong>Goodbye!</strong>", "substitution_tag": "unsubscribe", "text": "Goodbye" } } }''') )
def build_kitchen_sink(): """All settings set""" from sendgrid.helpers.mail import ( Mail, From, To, Cc, Bcc, Subject, PlainTextContent, HtmlContent, SendGridException, Substitution, Header, CustomArg, SendAt, Content, MimeType, Attachment, FileName, FileContent, FileType, Disposition, ContentId, TemplateId, Section, ReplyTo, Category, BatchId, Asm, GroupId, GroupsToDisplay, IpPoolName, MailSettings, BccSettings, BccSettingsEmail, BypassListManagement, FooterSettings, FooterText, FooterHtml, SandBoxMode, SpamCheck, SpamThreshold, SpamUrl, TrackingSettings, ClickTracking, SubscriptionTracking, SubscriptionText, SubscriptionHtml, SubscriptionSubstitutionTag, OpenTracking, OpenTrackingSubstitutionTag, Ganalytics, UtmSource, UtmMedium, UtmTerm, UtmContent, UtmCampaign) import time import datetime message = Mail() # Define Personalizations message.to = To('*****@*****.**', 'Example User1', p=0) message.to = [ To('*****@*****.**', 'Example User2', p=0), To('*****@*****.**', 'Example User3', p=0) ] message.cc = Cc('*****@*****.**', 'Example User4', p=0) message.cc = [ Cc('*****@*****.**', 'Example User5', p=0), Cc('*****@*****.**', 'Example User6', p=0) ] message.bcc = Bcc('*****@*****.**', 'Example User7', p=0) message.bcc = [ Bcc('*****@*****.**', 'Example User8', p=0), Bcc('*****@*****.**', 'Example User9', p=0) ] message.subject = Subject('Sending with SendGrid is Fun 0', p=0) message.header = Header('X-Test1', 'Test1', p=0) message.header = Header('X-Test2', 'Test2', p=0) message.header = [ Header('X-Test3', 'Test3', p=0), Header('X-Test4', 'Test4', p=0) ] message.substitution = Substitution('%name1%', 'Example Name 1', p=0) message.substitution = Substitution('%city1%', 'Example City 1', p=0) message.substitution = [ Substitution('%name2%', 'Example Name 2', p=0), Substitution('%city2%', 'Example City 2', p=0) ] message.custom_arg = CustomArg('marketing1', 'true', p=0) message.custom_arg = CustomArg('transactional1', 'false', p=0) message.custom_arg = [ CustomArg('marketing2', 'false', p=0), CustomArg('transactional2', 'true', p=0) ] message.send_at = SendAt(1461775051, p=0) message.to = To('*****@*****.**', 'Example User10', p=1) message.to = [ To('*****@*****.**', 'Example User11', p=1), To('*****@*****.**', 'Example User12', p=1) ] message.cc = Cc('*****@*****.**', 'Example User13', p=1) message.cc = [ Cc('*****@*****.**', 'Example User14', p=1), Cc('*****@*****.**', 'Example User15', p=1) ] message.bcc = Bcc('*****@*****.**', 'Example User16', p=1) message.bcc = [ Bcc('*****@*****.**', 'Example User17', p=1), Bcc('*****@*****.**', 'Example User18', p=1) ] message.header = Header('X-Test5', 'Test5', p=1) message.header = Header('X-Test6', 'Test6', p=1) message.header = [ Header('X-Test7', 'Test7', p=1), Header('X-Test8', 'Test8', p=1) ] message.substitution = Substitution('%name3%', 'Example Name 3', p=1) message.substitution = Substitution('%city3%', 'Example City 3', p=1) message.substitution = [ Substitution('%name4%', 'Example Name 4', p=1), Substitution('%city4%', 'Example City 4', p=1) ] message.custom_arg = CustomArg('marketing3', 'true', p=1) message.custom_arg = CustomArg('transactional3', 'false', p=1) message.custom_arg = [ CustomArg('marketing4', 'false', p=1), CustomArg('transactional4', 'true', p=1) ] message.send_at = SendAt(1461775052, p=1) message.subject = Subject('Sending with SendGrid is Fun 1', p=1) # The values below this comment are global to entire message message.from_email = From('*****@*****.**', 'DX') message.reply_to = ReplyTo('*****@*****.**', 'DX Reply') message.subject = Subject('Sending with SendGrid is Fun 2') message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python') message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>') message.content = [ Content('text/calendar', 'Party Time!!'), Content('text/custom', 'Party Time 2!!') ] message.attachment = Attachment(FileContent('base64 encoded content 1'), FileType('application/pdf'), FileName('balance_001.pdf'), Disposition('attachment'), ContentId('Content ID 1')) message.attachment = [ Attachment(FileContent('base64 encoded content 2'), FileType('image/png'), FileName('banner.png'), Disposition('inline'), ContentId('Content ID 2')), Attachment(FileContent('base64 encoded content 3'), FileType('image/png'), FileName('banner2.png'), Disposition('inline'), ContentId('Content ID 3')) ] message.template_id = TemplateId('13b8f94f-bcae-4ec6-b752-70d6cb59f932') message.section = Section('%section1%', 'Substitution for Section 1 Tag') message.section = [ Section('%section2%', 'Substitution for Section 2 Tag'), Section('%section3%', 'Substitution for Section 3 Tag') ] message.header = Header('X-Test9', 'Test9') message.header = Header('X-Test10', 'Test10') message.header = [ Header('X-Test11', 'Test11'), Header('X-Test12', 'Test12') ] message.category = Category('Category 1') message.category = Category('Category 2') message.category = [ Category('Category 1'), Category('Category 2') ] message.custom_arg = CustomArg('marketing5', 'false') message.custom_arg = CustomArg('transactional5', 'true') message.custom_arg = [ CustomArg('marketing6', 'true'), CustomArg('transactional6', 'false') ] message.send_at = SendAt(1461775053) message.batch_id = BatchId("HkJ5yLYULb7Rj8GKSx7u025ouWVlMgAi") message.asm = Asm(GroupId(1), GroupsToDisplay([1,2,3,4])) message.ip_pool_name = IpPoolName("IP Pool Name") mail_settings = MailSettings() mail_settings.bcc_settings = BccSettings(False, BccSettingsTo("*****@*****.**")) mail_settings.bypass_list_management = BypassListManagement(False) mail_settings.footer_settings = FooterSettings(True, FooterText("w00t"), FooterHtml("<string>w00t!<strong>")) mail_settings.sandbox_mode = SandBoxMode(True) mail_settings.spam_check = SpamCheck(True, SpamThreshold(5), SpamUrl("https://example.com")) message.mail_settings = mail_settings tracking_settings = TrackingSettings() tracking_settings.click_tracking = ClickTracking(True, False) tracking_settings.open_tracking = OpenTracking(True, OpenTrackingSubstitutionTag("open_tracking")) tracking_settings.subscription_tracking = SubscriptionTracking( True, SubscriptionText("Goodbye"), SubscriptionHtml("<strong>Goodbye!</strong>"), SubscriptionSubstitutionTag("unsubscribe")) tracking_settings.ganalytics = Ganalytics( True, UtmSource("utm_source"), UtmMedium("utm_medium"), UtmTerm("utm_term"), UtmContent("utm_content"), UtmCampaign("utm_campaign")) message.tracking_settings = tracking_settings return message.get()
message.from_email = From('*****@*****.**', 'DX') message.reply_to = ReplyTo('*****@*****.**', 'DX Reply') message.subject = Subject('Sending with SendGrid is Fun 2') message.content = Content(MimeType.text, 'and easy to do anywhere, even with Python') message.content = Content(MimeType.html, '<strong>and easy to do anywhere, even with Python</strong>') message.content = [ Content('text/calendar', 'Party Time!!'), Content('text/custom', 'Party Time 2!!') ] message.attachment = Attachment(FileContent('base64 encoded content 1'), FileType('application/pdf'), FileName('balance_001.pdf'), Disposition('attachment'), ContentId('Content ID 1')) message.attachment = [ Attachment(FileContent('base64 encoded content 2'), FileType('image/png'), FileName('banner.png'), Disposition('inline'), ContentId('Content ID 2')), Attachment(FileContent('base64 encoded content 3'), FileType('image/png'), FileName('banner2.png'), Disposition('inline'), ContentId('Content ID 3')) ]