def send_checklist_notice(self, author_mail, checklist): """ Send notice :type author_mail: str :type checklist: model.Checklist """ # check email author_mail = author_mail.lower() match = re.match(r'^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', author_mail) if match is None: logger.error('E-mail adddress %s is wrong', author_mail) return sg_client = sendgrid.SendGridAPIClient(apikey=self.api_key) from_email = Email('*****@*****.**') to_email = Email(author_mail) subject = "[SecretShopper] АЗС #{0}".format(checklist.object_info.num) body = "<h2>Контрольный лист посещения сохранен</h2>\ <p>Для исправления анкеты необходимо перейти по ссылке \ <a href='https://secret-shopper.net/checklist/edit/{0}'>https://secret-shopper.net/checklist/edit/{0}</a></p>\ <p>Для добавления файлов воспользуйтесь ссылкой \ <a href='https://secret-shopper.net/checklist/addfiles/{0}'>https://secret-shopper.net/checklist/addfiles/{0}</a></p>\ <p><br/><br/><br/><br/><br/><hr /><small>Это сообщение сформировано автоматически, на него не нужно отвечать.</small>\ </p>".format(checklist.uid) content = Content("text/html", body) mail = Mail(from_email, subject, to_email, content) if MailProvider.manager_email != '': logger.debug('CC: %s', MailProvider.manager_email) mail.personalizations[0].add_cc(Email(MailProvider.manager_email)) mail_response = sg_client.client.mail.send.post(request_body=mail.get()) if mail_response.status_code != 202: logger.error('Cant send email. Error is "%s"', mail_response.body) else: logger.info('E-mail sent') return
def test_helloEmail(self): self.maxDiff = None """Minimum required to send an email""" mail = Mail() mail.from_email = Email("*****@*****.**") mail.subject = "Hello World from the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**")) mail.add_personalization(personalization) mail.add_content(Content("text/plain", "some text here")) mail.add_content( Content( "text/html", "<html><body>some text here</body></html>")) self.assertEqual( json.dumps( mail.get(), sort_keys=True), '{"content": [{"type": "text/plain", "value": "some text here"}, ' '{"type": "text/html", ' '"value": "<html><body>some text here</body></html>"}], ' '"from": {"email": "*****@*****.**"}, "personalizations": ' '[{"to": [{"email": "*****@*****.**"}]}], ' '"subject": "Hello World from the SendGrid Python Library"}' ) self.assertTrue(isinstance(str(mail), str))
def send_email(tos, subject, **attributes): import sendgrid from sendgrid.helpers.mail import Email, Content, Mail first_to = tos[0] sg = sendgrid.SendGridAPIClient(apikey=config.sendgrid_config['sendgrid_api_key']) from_email = Email('*****@*****.**') to_email = Email(first_to) body = attributes.get('body', None) html = attributes.get('html', None) if body: content = Content('text/plain', body) elif html: content = Content('text/html', html) message = Mail(from_email, subject, to_email, content) for additional_to in tos[1:]: message.personalizations[0].add_to(Email(additional_to)) bccs = attributes.get('bccs', []) for bcc in bccs: message.personalizations[0].add_bcc(Email(bcc)) logging.info('sending mail "%s" to "%s"', subject, tos) response = sg.client.mail.send.post(request_body=message.get()) logging.debug('sent mail with status code %d', response.status_code)
def send_api_mail(subject, to, body): sg = sendgrid.SendGridAPIClient(apikey=os.getenv('SENDGRID_API_KEY')) from_email = SGEmail('Grey Li <*****@*****.**>') to_email = SGEmail(to) content = Content("text/plain", body) email = SGMail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=email.get())
def sendNewProjectEmail(project, owner, members): """ Send a notification email to the specified 'members' of the new 'project' created by 'owner'. """ template_values = { "owner" : owner.name, "project_name" : project.name, "project_id" : project.key.urlsafe() } subject = "[Expense Tracker] {} added you to project {}!".format( owner.name, project.name ) template_location = "templates/newProjectEmail.html" template = JINJA_ENVIRONMENT.get_template(template_location) for member in members: #if participant is owner: # continue # don't send email to owner of the project template_values["name"] = member["name"] template_values["is_admin"] = member["isAdmin"] to_email = Email(email=member["email"], name=member["name"]) content = Content(type="text/html", value=template.render(template_values)) mail = Mail(SENDER, subject, to_email, content) SG.client.mail.send.post(request_body=mail.get())
def send_email(email, name): from_email = Email("*****@*****.**") to_email = Email(email) subject = "Welcome" content = Content("text/plain", BODY.format(name)) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get())
def sendgrid_email(user,recipient,subject,body): sg = sendgrid.SendGridAPIClient(apikey=SendGridAPIKey) from_email = Email(user) to_email = Email(recipient) content = Content("text/plain",body) mail = Mail(from_email,subject,to_email,content) response = sg.client.mail.send.post(request_body=mail.get())
def test_unicode_values_in_substitutions_helper(self): """ Test that the Substitutions helper accepts unicode values """ self.maxDiff = None """Minimum required to send an email""" mail = Mail() mail.from_email = Email("*****@*****.**") mail.subject = "Testing unicode substitutions with the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**")) personalization.add_substitution(Substitution("%city%", u"Αθήνα")) mail.add_personalization(personalization) mail.add_content(Content("text/plain", "some text here")) mail.add_content( Content( "text/html", "<html><body>some text here</body></html>")) expected_result = { "content": [ { "type": "text/plain", "value": "some text here" }, { "type": "text/html", "value": "<html><body>some text here</body></html>" } ], "from": { "email": "*****@*****.**" }, "personalizations": [ { "substitutions": { "%city%": u"Αθήνα" }, "to": [ { "email": "*****@*****.**" } ] } ], "subject": "Testing unicode substitutions with the SendGrid Python Library", } self.assertEqual( json.dumps(mail.get(), sort_keys=True), json.dumps(expected_result, sort_keys=True) )
def send_email(subject, to, template_name, context): sendgrid_client = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) from_email = sendgrid.Email(settings.DEFAULT_FROM_EMAIL) to_email = sendgrid.Email(to) content = Content("text/plain", render_to_string(template_name, context)) mail = Mail(from_email, subject, to_email, content) return sendgrid_client.client.mail.send.post(request_body=mail.get())
def sendEmailSendGrid(subject, sender, to, body): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email(sender) to_email = Email(to) content = Content("text/plain", body) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) return response.status_code == 202 #print(response.status_code) #print(response.body) #print(response.headers)
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', **kwargs): """ Send an email with html content using sendgrid. To use this plugin: 0. include sendgrid subpackage as part of your Airflow installation, e.g., pip install airflow[sendgrid] 1. update [email] backend in airflow.cfg, i.e., [email] email_backend = airflow.contrib.utils.sendgrid.send_email 2. configure Sendgrid specific environment variables at all Airflow instances: SENDGRID_MAIL_FROM={your-mail-from} SENDGRID_API_KEY={your-sendgrid-api-key}. """ mail = Mail() mail.from_email = Email(os.environ.get('SENDGRID_MAIL_FROM')) mail.subject = subject # Add the recipient list of to emails. personalization = Personalization() to = get_email_address_list(to) for to_address in to: personalization.add_to(Email(to_address)) if cc: cc = get_email_address_list(cc) for cc_address in cc: personalization.add_cc(Email(cc_address)) if bcc: bcc = get_email_address_list(bcc) for bcc_address in bcc: personalization.add_bcc(Email(bcc_address)) mail.add_personalization(personalization) mail.add_content(Content('text/html', html_content)) # Add custom_args to personalization if present pers_custom_args = kwargs.get('personalization_custom_args', None) if isinstance(pers_custom_args, dict): for key in pers_custom_args.keys(): personalization.add_custom_arg(CustomArg(key, pers_custom_args[key])) # Add email attachment. for fname in files or []: basename = os.path.basename(fname) attachment = Attachment() with open(fname, "rb") as f: attachment.content = base64.b64encode(f.read()) attachment.type = mimetypes.guess_type(basename)[0] attachment.filename = basename attachment.disposition = "attachment" attachment.content_id = '<%s>' % basename mail.add_attachment(attachment) _post_sendgrid_mail(mail.get())
def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): contact_name = request.POST.get( 'contact_name' , '') contact_email = request.POST.get( 'contact_email' , '') form_content = request.POST.get('content', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content, } content = Content('text/plain', template.render(context)) #email = EmailMessage( # "New contact form submission", # content, # "Your website" +'', # ['*****@*****.**'], # headers = {'Reply-To': contact_email } #) #email.send() print(content, contact_email) #send_mail("New contact form submission", content, "*****@*****.**", ['*****@*****.**'], fail_silently=False) sg = sendgrid.SendGridAPIClient(apikey='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') from_email = Email(contact_email) subject = "Contact Form message from PUfP" to_email = Email("*****@*****.**") mail = Mail(from_email, subject, to_email, content) response=sg.client.mail.send.post(request_body=mail.get()) print("RESPONSE:" + str(response.status_code)) print("done") return redirect('contact') return render(request, 'contact.html', { 'form': form_class, })
def test_unicode_values_in_substitutions_helper(self): from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail( from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent( 'and easy to do anywhere, even with Python'), html_content=HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>')) message.substitution = Substitution('%city%', u'Αθήνα', p=1) self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] }, { "substitutions": { "%city%": "Αθήνα" } } ], "subject": "Sending with SendGrid is Fun" }''') )
def send_email(subject, content): sendgrid_client = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject=subject, plain_text_content=content, ) sand_box = os.environ.get('SAND_BOX') if sand_box == 'true': mail_settings = MailSettings() mail_settings.sandbox_mode = SandBoxMode(True) message.mail_settings = mail_settings return sendgrid_client.send(message)
def handle(self, *args, **options): if not hasattr(settings, 'SENDGRID_API_KEY'): return if not settings.SENDGRID_API_KEY: return sg_api = SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) msg_ids = EmailMessage.objects.filter(status__isnull=True).values('id') for msg_id in msg_ids: # We're going to be altering messages in the course of this loop, # so let's iterate over the IDs and not the message objects # themselves. # Note that values() returns a list of dicts, {'field_name': value}. message = EmailMessage.objects.get(id=msg_id['id']) from_email = Email("*****@*****.**") to_email = Email(message.address) try: subject = message.emailtype.subject.format( first_name=message.first_name, last_name=message.last_name) except KeyError: # If users have screwed up entering {first_name} or {last_name}, # format() will throw a KeyError. subject = 'About your ALA committee volunteering' try: body = message.emailtype.body.format( first_name=message.first_name, last_name=message.last_name) except KeyError: # This may look like a bad mail merge, but we can't anticipate # a substitute. body = message.emailtype.body content = Content("text/plain", body) mail = Mail(from_email, subject, to_email, content) response = sg_api.client.mail.send.post(request_body=mail.get()) message.status = response.status_code message.save()
def airtime_mail(amount, telephone_number, date, balance): message = Mail( from_email=app.config['MAIL_SENDER'], to_emails='*****@*****.**' ) message.dynamic_template_data = { 'subject': app.config['EMAIL_SUBJECT'], 'amount': amount, 'telephone': telephone_number, 'date': date, 'balance': balance } message.template_id = 'd-2b1a13d647ef4b329acb7e3e63c41f97' sg = SendGridAPIClient(app.config['SENDGRID_API_KEY']) response = sg.send(message)
def test_sendgrid_api_key(self): """Tests if including SendGrid API will throw an Exception""" # Minimum required to send an email self.max_diff = None mail = Mail() mail.from_email = Email("*****@*****.**") mail.subject = "Hello World from the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**")) mail.add_personalization(personalization) # Try to include SendGrid API key try: mail.add_content( Content( "text/plain", "some SG.2123b1B.1212lBaC here")) mail.add_content( Content( "text/html", "<html><body>some SG.Ba2BlJSDba.232Ln2 here</body></html>")) self.assertEqual( json.dumps( mail.get(), sort_keys=True), '{"content": [{"type": "text/plain", "value": "some text here"}, ' '{"type": "text/html", ' '"value": "<html><body>some text here</body></html>"}], ' '"from": {"email": "*****@*****.**"}, "personalizations": ' '[{"to": [{"email": "*****@*****.**"}]}], ' '"subject": "Hello World from the SendGrid Python Library"}' ) # Exception should be thrown except Exception: pass # Exception not thrown else: self.fail("Should have failed as SendGrid API key included")
def sendNewTransactionEmail(project, expense): """ Send an email to all relevant members in the specified 'project' for the specified 'expense'. """ payer = expense.paid_by.get() individualAmount = {ia.user_key:ia.amount for ia in expense.individual_amount} members = project.getMembers() template_values = { "project_name" : project.name, "payer" : payer.name, "expense" : { "transaction_date" : expense.transaction_date, "amount" : expense.amount, "details" : expense.details }, "splits" : calculateSplit(members, individualAmount) } template_location = "templates/newTransactionEmail.html" template = JINJA_ENVIRONMENT.get_template(template_location) subject = "[{}] {} paid ${:.2f} for {}".format(project.name, payer.name, expense.amount, expense.details) content = Content(type="text/html", value=template.render(template_values)) recipients = determineRecipients(project, members, individualAmount, payer) for recipient in recipients: to_email = Email(email=recipient.email, name=recipient.name) mail = Mail(SENDER, subject, to_email, content) try: response = SG.client.mail.send.post(request_body=mail.get()) except: pass
def send_email(self, **opts): if not opts.get('from_email', None) and not self.default_from: raise ValueError('No from email or default_from was configured') sg = sendgrid.SendGridAPIClient(apikey=self.api_key) to_email = Email(opts.get('to_email')) from_email = Email(opts.get('from_email', None) or self.default_from) subject = opts['subject'] if opts.get('html', None): content = Content('html', opts['html']) elif opts.get('text', None): content = Content('text/plain', opts['text']) mail = Mail(from_email, subject, to_email, content) data = mail.get() response = sg.client.mail.send.post(request_body=data) return response.status_code
def send_download_link(to, export_results): """ Sends an email containing the export download link to a user Args: to (string): The email of the recipient. export_results (array): A dictionary containing two keys, succeeded and failed, which both contain an array of objects with the video title and last updated timestamp. Returns: (Response): SendGrid response object. """ to_mail = sendgrid.Email(to) content = render_mail_content(export_results) message = Mail(from_email=from_mail, subject='Your AchSo! video export is finished', to_email=to_mail, content=content) resp = sg.client.mail.send.post(request_body=message.get()) return resp
def send_checklist_verified(self, checklist): """ Send e-mail to authorities """ if MailProvider.customer_email == '': return sg_client = sendgrid.SendGridAPIClient(apikey=self.api_key) from_email = Email('*****@*****.**') to_email = Email(MailProvider.customer_email) subject = "[SecretShopper] АЗС #{0} добавлена".format(checklist.object_info.num) body = "<h2>Контрольный лист посещения добавлен</h2>\ <p>Для просмотра анкеты необходимо перейти по ссылке \ <a href='https://secret-shopper.net/checklist/edit/{0}'>https://secret-shopper.net/checklist/edit/{0}</a></p>\ <p><br/><br/><br/><br/><br/><hr /><small>Это сообщение сформировано автоматически, на него не нужно отвечать.</small>\ </p>".format(checklist.uid) content = Content("text/html", body) mail = Mail(from_email, subject, to_email, content) mail_response = sg_client.client.mail.send.post(request_body=mail.get()) if mail_response.status_code != 202: logger.error('Cant send email. Error is "%s"', mail_response.body) return
def send_sendgrid(sendgrid_api_key=None, github_email_template=None, github_user_emails=None): assert sendgrid_api_key, "SendGrid API key is required" sg = SendGridAPIClient(apikey=sendgrid_api_key) metadata = github_email_template.metadata from_email = Email(metadata['from']) from_email.name = metadata['from_name'] for ge in github_user_emails: # Add github_user into metadata metadata['user'] = ge # Render content with metadata content = Content("text/html", github_email_template.render_content(metadata)) # Render subject with metadata subject = template_env.from_string(metadata['subject']).render(metadata) to_email = Email(ge.email) mail = Mail(from_email, subject, to_email, content) _body = mail.get() # Add custom args for log fields _custon = {} for key, value in metadata.iteritems(): if key not in ESSENTIAL_FIELDS: _custon[key] = value _custon['repository'] = metadata['repository'] _body['custom_args'] = _custon response = sg.client.mail.send.post(request_body=_body) if response.status_code > 300: # More than 300 means something wrong, do nothing. sys.exit()
def build_hello_email(): ## Send a Single Email to a Single Recipient import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException message = Mail(from_email=From('*****@*****.**', 'Example From Name'), to_emails=To('*****@*****.**', 'Example To Name'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>')) try: print(json.dumps(message.get(), sort_keys=True, indent=4)) return message.get() except SendGridException as e: print(e.message) for cc_addr in personalization['cc_list']: mock_personalization.add_to(cc_addr) for bcc_addr in personalization['bcc_list']: mock_personalization.add_bcc(bcc_addr) for header in personalization['headers']: mock_personalization.add_header(header) for substitution in personalization['substitutions']: mock_personalization.add_substitution(substitution) for arg in personalization['custom_args']: mock_personalization.add_custom_arg(arg) mock_personalization.subject = personalization['subject'] mock_personalization.send_at = personalization['send_at'] return mock_personalization
def sendgrid_handler(self, queue_message, to_addrs_to_email_messages_map): self.logger.info("Sending account:%s policy:%s %s:%s email:%s to %s" % ( queue_message.get('account', ''), queue_message['policy']['name'], queue_message['policy']['resource'], str(len(queue_message['resources'])), queue_message['action'].get('template', 'default'), to_addrs_to_email_messages_map)) from_email = Email(self.config.get('from_address', '')) subject = get_message_subject(queue_message) email_format = queue_message['action'].get('template_format', None) if not email_format: email_format = queue_message['action'].get( 'template', 'default').endswith('html') and 'html' or 'plain' for email_to_addrs, email_content in six.iteritems(to_addrs_to_email_messages_map): for to_address in email_to_addrs: to_email = Email(to_address) content = Content("text/" + email_format, email_content) mail = Mail(from_email, subject, to_email, content) try: self.sendgrid_client.client.mail.send.post(request_body=mail.get()) except (exceptions.UnauthorizedError, exceptions.BadRequestsError) as e: self.logger.warning( "\n**Error \nPolicy:%s \nAccount:%s \nSending to:%s \n\nRequest body:" "\n%s\n\nRequest headers:\n%s\n\n mailer.yml: %s" % ( queue_message['policy'], queue_message.get('account', ''), email_to_addrs, e.body, e.headers, self.config ) ) return False return True
def _setup_email(_notify): mail = Mail() mail.from_email = Email(**_notify.from_email) for attachment in _notify.attachment_list(): _att = Attachment() _att.content = gb64(attachment) _att.filename = os.path.split(attachment)[-1] _att.disposition = "attachment" mail.add_attachment(_att) mail.add_content(Content("text/html", _notify.message)) return mail
def add_User(request, pk): entity = get_object_or_404(Entity, pk=pk) if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): UserProfileInfo = form.save(commit=False) UserProfileInfo.entity = entity UserProfileInfo.save() subject = 'Your Fafnir account is set!' message = "Hi, Testing" message = Mail(from_email='*****@*****.**', to_emails=["*****@*****.**"], subject=subject, html_content=message) sg = SendGridAPIClient(SENDGRID_API_KEY) response = sg.send(message) """ name = form.cleaned_data["name"] email = form.cleaned_data["email"] subject = f'Message from {form.cleaned_data["name"]}' message = "Welcome to My Portal" sender = "*****@*****.**" recipients = ['*****@*****.**', "*****@*****.**"] try: jj = send_mail(subject, message, sender, recipients, fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found') """ return redirect('users', pk=entity.pk) else: form = UserForm() entity_list = Entity.objects.order_by('entity_name') return render(request, 'first_app/add_user.html', {'form': form})
def notify_manager_unapprovement(trigger_check, metric_log): print("notify_manager_unapprovement: Starting...") offer = models.Offer.objects.get(pk=metric_log.offer_id) sg = sendgrid.SendGridAPIClient(apikey=settings.SENDGRID_API_KEY) now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") html = f""" Affiliate ID: {metric_log.affiliate_id} was UNAPPROVED from offer {offer.name} - lost ${metric_log.value} <br><br> <small>generated at: {now}</small> """ from_email = Email(settings.NETWORK_EMAIL) subject = ('Affiliate was PAUSED due to click cost! ' f'Offer {metric_log.offer_id}') content = Content("text/html", html) for recipient in Recipient.objects.filter(active=True): to_email = Email(recipient.email) mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=mail.get()) # SEND TO MANAGER api = Hasoffers(network_token=settings.HASOFFERS_NETWORK_TOKEN, network_id=settings.HASOFFERS_NETWORK_ID, proxies=settings.PROXIES) affiliate = (api.Affiliate.findById( id=metric_log.affiliate_id).extract_one()) employee = models.Employee.objects.get(pk=affiliate.account_manager_id) email_address = (employee.email if not employee.use_secondary else employee.secondary_email) to_email = Email(email_address) mail = Mail(from_email, subject, to_email, content) res = sg.client.mail.send.post(request_body=mail.get()) print(f'notify_manager_unapprovement: ' f'affiliate_id={metric_log.affiliate_id} ' f'offer_id={metric_log.offer_id} ' f'trigger_check_id={trigger_check.id}') return str(res)
def send(self, message, envelope_from=None): assert message.send_to, "No recipients have been added" assert message.sender, ( "The message does not specify a sender and a default sender " "has not been configured") if message.has_bad_headers(): raise BadHeaderError if message.date is None: message.date = time.time() if not message.subject: message.subject = word("(no subject)") sgmessage = SGMail( from_email=Email(message.sender), to_emails=[To(addressee) for addressee in sanitize_addresses(message.recipients)], subject=message.subject, plain_text_content=message.body, html_content=message.html) if message.cc: for recipient in list(sanitize_addresses(message.cc)): sgmessage.add_cc(recipient) if message.bcc: for recipient in list(sanitize_addresses(message.bcc)): sgmessage.add_bcc(recipient) if message.attachments: for flask_attachment in message.attachments: attachment = Attachment() attachment.file_content = FileContent(base64.b64encode(flask_attachment.data).decode()) attachment.file_type = FileType(flask_attachment.content_type) attachment.file_name = FileName(flask_attachment.filename) attachment.disposition = Disposition(flask_attachment.disposition) sgmessage.add_attachment(attachment) sg = SendGridAPIClient(self.mail.api_key) response = sg.send(sgmessage) if response.status_code >= 400: sys.stderr.write("SendGrid status code: " + str(response.status_code) + "\n") sys.stderr.write("SendGrid response headers: " + repr(response.headers) + "\n") try: sys.stderr.write(repr(response.body) + "\n") except: pass raise Exception("Failed to send e-mail message to SendGrid") email_dispatched.send(message, app=current_app._get_current_object())
def send_email_task_sendgrid(payload): message = Mail( from_email=From(payload['from'], payload['fromname']), to_emails=payload['to'], subject=payload['subject'], html_content=payload["html"], ) if payload['bcc'] is not None: message.bcc = payload['bcc'] if payload['reply_to'] is not None: message.reply_to = payload['reply_to'] if payload['attachments'] is not None: for filename in payload['attachments']: with open(filename, 'rb') as f: file_data = f.read() f.close() encoded = base64.b64encode(file_data).decode() attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.disposition = Disposition('attachment') if filename.endswith('.pdf'): attachment.file_type = FileType('application/pdf') attachment.file_name = FileName(filename) elif filename.endswith('.ics'): attachment.file_type = FileType('text/calendar') attachment.file_name = FileName('ical.ics') message.add_attachment(attachment) sendgrid_client = SendGridAPIClient(get_settings()['sendgrid_key']) logging.info( 'Sending an email to {} regarding "{}" on behalf of {}'.format( payload['to'], payload["subject"], payload["from"] ) ) try: 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) elif e.code == 554: empty_attachments_send(sendgrid_client, message) else: logging.exception(f"The following error has occurred with sendgrid-{str(e)}")
def email(sendee_email="*****@*****.**", sentiment=1): import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail if sentiment == 1: content = "Thank you for the review! Glad you had a great time and hope to see you again!" else: content = "Sorry, that you didn't have a wonderful time. Please accept this promo code for 50% off your next experience! PROMO: SPRINGFUN2021" message = Mail(from_email=sendee_email, to_emails='*****@*****.**', subject='Coleman Corporation', html_content=f'<strong> {content} </strong>') 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: # pylint: disable=W0703 print(e.message) # pylint: disable=E1101
def send_email(listings: [Listing], sg: SendGridAPIClient, from_email: str, to_email: str): formatted_listings = [] for listing in listings: formatted_listing = "Title: {}<br>Price: {}<br>Link: {}".format( listing.title, listing.price, listing.link) formatted_listings.append(formatted_listing) now = datetime.now() now_string = now.strftime("%d/%m/%y %H:%M") if len(formatted_listings): message_contents = "<br><br>".join(formatted_listings) else: message_contents = "No listings." message = Mail(from_email=from_email, to_emails=to_email, subject="Head-Fi Classifieds Feed @ {}".format(now_string), html_content=message_contents) try: response = sg.send(message) except Exception as e: print(e.message)
def done(self, form_list, **kwargs): form_data = {} for f in form_list: form_data.update(f.cleaned_data) user_list = form_data.get('user_list', []) for user in user_list: user.profile.cases.add(self.instance) if settings.SENDGRID_KEY: sg = sendgrid.SendGridAPIClient(settings.SENDGRID_KEY) current_site = get_current_site(self.request) for invited in user_list: context = {} context.update(form_data) context.update({ 'case': self.instance, 'user': self.request.user, 'invited': invited, 'case_url': 'https://%s%s' % (current_site.domain, reverse('case', kwargs={'pk': self.instance.id})), }) body = render_to_string('cases/mail/invite.txt', context) email = Mail( from_email='noreply@%s' % current_site.domain, to_emails=invited.username, subject='Omslagroute - je bent toegevoegd aan een team', plain_text_content=body) sg.send(email) messages.add_message( self.request, messages.INFO, "De nieuwe gebruikers hebben een email gekregen van hun uitnodiging." ) return HttpResponseRedirect(self.get_success_url())
def create_user(self, claims): user = super().create_user(claims) user.meta = { 'claims': claims, } user = self.update_user_federation(user, claims) user.save() profile = Profile() profile.user = user profile.save() beheerder_recipient_list = list(self.UserModel.objects.beheerders().values_list('username', flat=True)) federation = Federation.objects.filter(federation_id=claims.get(settings.OIDC_FEDERATION_KEY)).first() if federation and federation.organization and federation.organization.federation_type: federatie_beheerder_recipient_list = list(self.UserModel.objects.federation_beheerders_by_federation( federation, federation.organization.federation_type ).values_list('username', flat=True)) if federatie_beheerder_recipient_list: beheerder_recipient_list = federatie_beheerder_recipient_list if settings.SENDGRID_KEY and beheerder_recipient_list: current_site = get_current_site(self.request) data = { 'site': current_site.domain, 'url': reverse('update_user', kwargs={'pk': user.id}) } body = render_to_string('users/mail/gebruikers_beheerders_new_user.txt', data) sg = sendgrid.SendGridAPIClient(settings.SENDGRID_KEY) email = Mail( from_email='no-reply@%s' % current_site.domain, to_emails=beheerder_recipient_list, subject='Omslagroute - gebruiker aangemaakt', plain_text_content=body ) sg.send(email) return user
def test_from_emailmessage(self): message = EmailMessage() body = 'message that is not urgent' try: message.set_content(body) except AttributeError: # Python2 message.set_payload(body) message.set_default_type('text/plain') message['Subject'] = 'URGENT TITLE' message['From'] = '*****@*****.**' message['To'] = '*****@*****.**' mail = Mail.from_EmailMessage(message) self.assertEqual(mail.subject.get(), 'URGENT TITLE') self.assertEqual(mail.from_email.email, '*****@*****.**') self.assertEqual(len(mail.personalizations), 1) self.assertEqual(len(mail.personalizations[0].tos), 1) self.assertEqual(mail.personalizations[0].tos[0], {'email': '*****@*****.**'}) self.assertEqual(len(mail.contents), 1) content = mail.contents[0] self.assertEqual(content.type, 'text/plain') self.assertEqual(content.value, 'message that is not urgent')
def confirm_identifier(magic: MagicLink): encoded = jwt.encode(jsonable_encoder(magic.dict()), JWT_SECRET, algorithm='HS256').decode('utf-8') print("Payload enconded to JWT: " + encoded) print("sending confirmation to: " + magic.identifier) message = Mail( from_email=os.environ.get('SENDGRID_SENDER'), to_emails=magic.identifier, subject='Are you a bot?', html_content='<a href="http://127.0.0.1:8000/validate/?token=' + encoded + '">Confirm you are human or a super smart bot: </a>') 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.body) return magic.payload
def notify(bucket, name): app.logger.info(f"notify with bucket '{bucket}' and name '{name}'") to_emails = os.environ.get('TO_EMAILS') image_url = f'https://storage.googleapis.com/{bucket}/{name}' app.logger.info(f"Sending email to '{to_emails}''") message = Mail( from_email='*****@*****.**', to_emails=to_emails, subject='A new chart from BigQuery Pipeline', html_content= f'A new chart is available for you to view: {image_url} <br><img src="{image_url}"/>' ) try: app.logger.info(f"Email content {message}") sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) app.logger.info(f"Email status code {response.status_code}") except Exception as e: print(e)
def enviar_email(dest_mail, dest_nome, assunto, mensagem): # E-mail do remetente email_remetente = os.environ.get('EMAIL_REMETENTE') # Cria mensagem para o destinatário message = Mail(from_email=email_remetente, to_emails=dest_mail, subject=assunto, html_content=mensagem) # Envia o e-mail try: print('Enviando e-mail para ' + dest_mail + ' com assunto ' + assunto) # Token da conta do SendGrid print('TOKEN = ' + os.environ.get('SENDGRID_TOKEN')) sg = SendGridAPIClient(os.environ.get('SENDGRID_TOKEN')) response = sg.send(message) print(response.status_code) print('E-mail enviado com sucesso!') except Exception as e: print(e)
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='Sending with Twilio SendGrid is Fun - New', html_content= '<strong>and easy to do anywhere, even with Python</strong>') try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) logging.info(response.status_code) logging.info(response.body) logging.info(response.headers) return func.HttpResponse("e-mail sent using sendgrid API", status_code=200) except Exception as e: logging.info(e.message) return func.HttpResponse("Error sending mail with sendgrid API", status_code=401)
def notify_about_comment(**kwargs): logging.info('Notified about new comment!') message = Mail( from_email='*****@*****.**', to_emails=kwargs.get('to_user_email'), subject='You got new comment on your post!', plain_text_content= 'You got comment "{comment}" by {user_commented} on post "{post}"'. format(post=kwargs.get('post_text'), comment=kwargs.get('comment_text'), user_commented=kwargs.get('from_user_email')), html_content=get_html_content_new_comment( kwargs.get('post_text'), kwargs.get('comment_text'), kwargs.get('from_user_email'))) try: sg = SendGridAPIClient(os.environ.get('EMAIL_API_KEY')) response = sg.send(message) logging.info(response.status_code) logging.info(response.body) except Exception as e: logging.error(e.message)
def sendEmail(template: EmailTemplate, email: str, subject: str, fromName='Lincoln Yan', fromEmail='*****@*****.**', templateOptions: dict = {}, **options) -> bool: if APIKEY: message = Mail( from_email=f'{fromName} <{fromEmail}>', to_emails=email, subject=subject, html_content=template(**templateOptions).Generate(**options)) try: sg = SendGridAPIClient(APIKEY) response = sg.send(message) return True except Exception as e: print(e) return False else: raise Exception('A sendgrid API key is required to send emails.')
def sendVerificationText(e_mail, userIdNo): _from = "*****@*****.**" _to = e_mail _subject = "Matcha's Account Verification" _text = "".join( ("<p>", "Matcha's team thanks you for signing up.", "<br>", "<br>", "Please click <a href=\"%s\">here</a> to activate your account." % ("http://0.0.0.0:4000/verify" + userIdNo), "<br>", "<br>", "Regards!", "</p>")) message = Mail(from_email=_from, to_emails=_to, subject=_subject, html_content=_text) try: sg = SendGridAPIClient("*") response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) print("A verification eMail was sent to %s" % e_mail) except Exception as e: print(e)
def sendemailaction(event): profile_user_id = event.source.user_id profile_name = line_bot_api.get_profile(event.source.user_id).display_name # print(profile_user_id) message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject=f'Line Chatbot;{profile_name}', html_content= f'<strong>有人使用Line Chatbot</strong><br>{profile_name}<br>{profile_user_id}' ) 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)
def notify_photo(id, grpcode, email, phone): num = randint(100, 999) cont = get_user(id) if len(cont['phone']) > 0 and phone: urlsrc = 'https://' + mydomain + '/g/' + grpcode + '#/connect/' + cont[ 'code'] items = get_one_by('groups', grpcode, 'key') client = Client(twilio_id, twilio_token) rl = current_user( )['name'] + " updated the gallery " + items[0]['name'] + ' ' + urlsrc message = client.messages.create(body=rl, from_='+1' + os.getenv('TWILIO_FROM'), to=cont['phone']) print('notify ' + cont['phone'], file=sys.stderr) if len(cont['email']) > 0 and email: owner = current_user() em = cont['email'] invitetext = ' updated the gallery ' items = get_one_by('groups', grpcode, 'key') imgsrc = '' if not items[0]['image'] is None: imgsrc = urllib.parse.quote(items[0]['image']) html = '<div style="font-family:courier,monospace;width:90%"><img alt="group image for ' + items[ 0]['name'] + '" style="height:auto;padding:30px;display:block;margin-left:auto;margin-right:auto;width:50%;padding:10px;" src="https://' + mydomain + '/grpFile?field=image&name=' html = html + imgsrc + '" /><p style="text-align:center;display:block;padding:10px;">' + owner[ 'name'] + invitetext + items[0][ 'name'] + '</p><a style="text-align:center;background-color:#32e0c4;display:block;color:black;text-decoration:none;padding:10px;" href="https://' + mydomain + '/g/' + grpcode + '#/connect/' + cont[ 'code'] + '">View Gallery</a></div>' regex = re.compile('[^a-zA-Z ]') oname = regex.sub('', owner['name']) message = Mail(from_email=oname + ' via ' + mydomain + ' <' + os.getenv('SENDGRID_FROM') + '>', to_emails=em, subject="Updated gallery, " + items[0]['name'], html_content=html) sg = SendGridAPIClient(sendgrid_token) response = sg.send(message) print('notify ' + em, file=sys.stderr) return True
def forgot(): form = user_forms.Forgot() if form.validate_on_submit(): user = models.User.query.filter_by(email=form.email.data).first() # Check the user exists if user is not None: # Subject of the confirmation email subject = 'Reset your password.' # Generate a random token token = ts.dumps(user.email, salt='password-reset-key') # Build a reset link with token resetUrl = url_for('userbp.reset', token=token, _external=True) # Render an HTML template to send by email html = render_template('email/reset.html', reset_url=resetUrl) # Send the email to user message = Mail(from_email='*****@*****.**', to_emails=user.email, subject=subject, html_content=render_template('email/reset.html', reset_url=resetUrl)) 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.message) #email.send(user.email, subject, html) # Send back to the home page flash('Check your emails to reset your password.', 'positive') return redirect(url_for('index')) else: flash('Unknown email address.', 'negative') return redirect(url_for('userbp.forgot')) return render_template('user/forgot.html', form=form)
def get_order_email(order) -> Mail: to_emails = [ # '*****@*****.**', '*****@*****.**', ] if order.email: to_emails.append(order.email) context = { 'order_identifier': f'ITG-{order.id}', 'invoice_url': f'{settings.FRONTEND_INVOICE_URL}/{order.id}' } return Mail( from_email=settings.DEFAULT_FROM_EMAIL, to_emails=to_emails, subject=f'[ITALGOLD] Porosia {context["order_identifier"]}', html_content=render_to_string( template_name='email/order_saved.html', context=context ) )
def post(self, request, *args, **kwargs): text = f""" <div> <h1>Ім'я: {request.data.get('name')}</h1> <h3>Номер: {request.data.get('cell')}</h3> <p>Текст: {request.data.get('message')}</p> </div> """ message = Mail( from_email='*****@*****.**', to_emails=['*****@*****.**', '*****@*****.**'], subject='Feedback from apteka-znahar.com.ua', html_content=text) try: sg = SendGridAPIClient(os.getenv("SENDGRID_API_KEY")) sg.send(message) except Exception as e: return Response({"message": str(e), "code": 400}, 400) return Response({"message": "success", "code": 201}, 201)
def sending_emial(self, contenido, cliente): """functions that sends the email verification""" message = Mail( from_email='*****@*****.**', to_emails=cliente.email, # to_emails='*****@*****.**', subject=f'Te Respondieron en CianCoders', html_content=render_to_string('emails/email_comentario.html', { 'contenido': contenido, })) try: sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) # print(response.status_code) # print(response.body) # print(response.headers) # print("se envio el mensaje") except Exception as e: print("noo envio el mensaje") print(e)
def send_email(msg): """Send email containing the message via sendgrid""" print(f"Trying to send email with msg: {msg}") # get destination address and API key from env vars dest_mail = os.getenv('EMAIL', None) api_key = os.environ.get('SENDGRID_API_KEY', None) if dest_mail is None or api_key is None: print( "Env var 'EMAIL' or 'SENDGRID_API_KEY' missing. Can't send email.") return "Env var 'EMAIL' or 'SENDGRID_API_KEY' missing. Can't send email." email = Mail(from_email='*****@*****.**', to_emails=dest_mail, subject='Quotify: Change Notification', html_content=msg) try: sg = SendGridAPIClient(api_key=api_key) response = sg.send(email) print(f"Email response status code: {response.status_code}") return f"Sent email with msg: {msg} to {dest_mail}. Status code: {response.status_code}" except Exception as e: print(e.message)
def get_redirect_url(self, *args, **kwargs): self.object = get_object_or_404(self.model, pk=kwargs['pk']) form_config = FORMS_BY_SLUG.get(self.kwargs.get('form_config_slug')) redirect_url = reverse('case', args=[ self.object.id, ]) recipient_list = self.request.user.federation.main_email_list current_site = get_current_site(self.request) body = render_to_string( 'cases/mail/validate_case.txt', { 'form_name': form_config.get('title'), 'case_url': 'https://%s%s' % ( current_site.domain, reverse('update_case', args=[ self.object.id, self.kwargs.get('form_config_slug'), ]), ), 'user': self.request.user, }) if settings.SENDGRID_KEY and recipient_list: sg = sendgrid.SendGridAPIClient(settings.SENDGRID_KEY) email = Mail(from_email='noreply@%s' % current_site.domain, to_emails=recipient_list, subject='Omslagroute - %s controleren' % form_config.get('title'), plain_text_content=body) sg.send(email) messages.add_message( self.request, messages.INFO, "De aanvraag is ter controle gestuurd naar '%s'." % (self.request.user.federation.name_form_validation_team if self.request.user.federation.name_form_validation_team else self.request.user.federation.name, )) return redirect_url
def create_email(address, subject, template_name, context): templateLoader = jinja2.FileSystemLoader(searchpath="templates") templateEnv = jinja2.Environment(loader=templateLoader) html_template = templateEnv.get_template(template_name + ".html") html_to_send = html_template.render(context) content = HtmlContent(html_to_send) from_email = From("*****@*****.**", "Unsub Team") to_email = To(address) to_emails = [to_email] if "mmu.ac.uk" in address: to_emails += [Cc("*****@*****.**")] email = Mail(from_email=from_email, subject=Subject(subject), to_emails=to_emails, html_content=content) logger.info((u'sending email "{}" to {}'.format(subject, address))) return email
def main(mytimer: func.TimerRequest) -> None: logging.info("hello how are you !") if mytimer.past_due: logging.info('The timer is past due!') sg = SendGridAPIClient( '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' ) logging.info(blob_service_client) logging.info(container_client) container_prop = container_client.get_container_properties() logging.info('shobhit' + str(container_prop.last_modified)) blob_last_modified = datetime.now() - timedelta(hours=300) for blob in container_client.list_blobs(): logging.info("blob last modified: " + str(blob.last_modified)) if blob.last_modified.replace(tzinfo=None) > blob_last_modified: blob_last_modified = blob.last_modified.replace(tzinfo=None) blob_last_upload = blob_last_modified.replace( tzinfo=None) # Both Time should be without time stamp current_time = datetime.now() logging.info("curent time : " + str(current_time)) time_delta = current_time - blob_last_upload logging.info("time delta : " + str(time_delta)) hour_diff = (time_delta.total_seconds() / 3600) logging.info("hour diff : " + str(hour_diff)) if hour_diff > 2: message = Mail( from_email='*****@*****.**', to_emails='*****@*****.**', subject='No Data recevied in last 2 hours ', html_content= 'The is to notify you that no data has been recevied in last : ' + str(round(hour_diff, 2)) + ' hours') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers)
def sendEmailWithSendGrid(customMessage): message = Mail( from_email='*****@*****.**', to_emails=customMessage["to_emails"], subject=customMessage["subject"], plain_text_content=customMessage["plain_text_content"], html_content=customMessage["html_content"]) try: sg = SendGridAPIClient ('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') response = sg.send(message) print('THE RESPONSE CODE IS:' + str(response.status_code)) print(response.body) print(response.headers) print('sent') except Exception as e: print("Exception occured") print(e) print(e.body)
def send_invite_email(email, displayname): from itsdangerous import TimedJSONWebSignatureSerializer def create_token(email, displayname, expiration=3600): private_key = current_app.config["SECRET_KEY"] serializer = TimedJSONWebSignatureSerializer(private_key, expiration) return serializer.dumps({ "email": email, "displayname": displayname }).decode("utf-8") try: register_link = url_for("register", token=create_token(email, displayname), _external=True) except: # This is dirty but the app is not all the way up yet so url_for is not generating proper urls register_link = f"http://{current_app.config['SERVER_NAME']}/admin/register?token={create_token(email, displayname)}" message = Mail( from_email=Email(current_app.config["BLOG_CONTACT_EMAIL"]), to_emails=To(email), subject="You've been invited to use TeamBlog!", html_content=render_template( "register_email.j2", name=displayname, link=register_link, ), ) try: sg = SendGridAPIClient(current_app.config["SENDGRID_API_KEY"]) sg.send(message) return True except Exception as e: print(e.message) return False
def send_email_custom(email_to, **mail_details): from flask import render_template from_email = '*****@*****.**' import pdb pdb.set_trace() msg_html = render_template('forgot.html', **mail_details) import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail message = Mail(from_email=from_email, to_emails=email_to, subject='Sending with Twilio SendGrid is Fun', html_content=msg_html) try: sg = SendGridAPIClient('nooooo') response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message)
def checkCinemaAndInformUsers(movieName, cinemaNames, cinemaNameToSearchFor): cinemasToInformFor = [] if cinemaNameToSearchFor is None: print "Matching all cinenmas!" cinemasToInformFor = cinemaNames else: print "Shortlisting cinemas with regex " + cinemaNameToSearchFor regex = re.compile(cinemaNameToSearchFor, flags=re.IGNORECASE) for cinema in cinemaNames: if regex.search(cinema): print "Cinema match ! " + cinema cinemasToInformFor.append(cinema) else: print "Not matching:" + cinema if len(cinemasToInformFor) == 0: print "No cinemas found for this movie that match the required pattern!!" return print "Sending mail for movie - " + movieName + ", cinemaName = " " ".join( cinemasToInformFor) message = Mail( from_email='*****@*****.**', to_emails=['*****@*****.**', '*****@*****.**'], subject='Tickets available for ' + movieName, html_content='<strong>Hey! Movie ticket are available for movie ' + movieName + ' with cinema ' + " ".join(cinemasToInformFor) + ' </strong>') 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.message)
def test_single_email_to_a_single_recipient_content_reversed(self): """Tests bug found in Issue-451 with Content ordering causing a crash """ from sendgrid.helpers.mail import (Mail, From, To, Subject, PlainTextContent, HtmlContent) self.maxDiff = None message = Mail() message.from_email = From('*****@*****.**', 'Example From Name') message.to = To('*****@*****.**', 'Example To Name') message.subject = Subject('Sending with SendGrid is Fun') message.content = HtmlContent( '<strong>and easy to do anywhere, even with Python</strong>') message.content = PlainTextContent( 'and easy to do anywhere, even with Python') self.assertEqual( message.get(), json.loads(r'''{ "content": [ { "type": "text/plain", "value": "and easy to do anywhere, even with Python" }, { "type": "text/html", "value": "<strong>and easy to do anywhere, even with Python</strong>" } ], "from": { "email": "*****@*****.**", "name": "Example From Name" }, "personalizations": [ { "to": [ { "email": "*****@*****.**", "name": "Example To Name" } ] } ], "subject": "Sending with SendGrid is Fun" }''') )
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', sandbox_mode=False, **kwargs): """ Send an email with html content using sendgrid. To use this plugin: 0. include sendgrid subpackage as part of your Airflow installation, e.g., pip install 'apache-airflow[sendgrid]' 1. update [email] backend in airflow.cfg, i.e., [email] email_backend = airflow.contrib.utils.sendgrid.send_email 2. configure Sendgrid specific environment variables at all Airflow instances: SENDGRID_MAIL_FROM={your-mail-from} SENDGRID_API_KEY={your-sendgrid-api-key}. """ if files is None: files = [] mail = Mail() from_email = kwargs.get('from_email') or os.environ.get('SENDGRID_MAIL_FROM') from_name = kwargs.get('from_name') or os.environ.get('SENDGRID_MAIL_SENDER') mail.from_email = Email(from_email, from_name) mail.subject = subject mail.mail_settings = MailSettings() if sandbox_mode: mail.mail_settings.sandbox_mode = SandBoxMode(enable=True) # Add the recipient list of to emails. personalization = Personalization() to = get_email_address_list(to) for to_address in to: personalization.add_to(Email(to_address)) if cc: cc = get_email_address_list(cc) for cc_address in cc: personalization.add_cc(Email(cc_address)) if bcc: bcc = get_email_address_list(bcc) for bcc_address in bcc: personalization.add_bcc(Email(bcc_address)) # Add custom_args to personalization if present pers_custom_args = kwargs.get('personalization_custom_args', None) if isinstance(pers_custom_args, dict): for key in pers_custom_args.keys(): personalization.add_custom_arg(CustomArg(key, pers_custom_args[key])) mail.add_personalization(personalization) mail.add_content(Content('text/html', html_content)) categories = kwargs.get('categories', []) for cat in categories: mail.add_category(Category(cat)) # Add email attachment. for fname in files: basename = os.path.basename(fname) attachment = Attachment() attachment.type = mimetypes.guess_type(basename)[0] attachment.filename = basename attachment.disposition = "attachment" attachment.content_id = '<{0}>'.format(basename) with open(fname, "rb") as f: attachment.content = base64.b64encode(f.read()).decode('utf-8') mail.add_attachment(attachment) _post_sendgrid_mail(mail.get())
## Send a Single Email to a Single Recipient import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException message = Mail(from_email=From('*****@*****.**', 'DX'), to_emails=To('*****@*****.**', 'Elmer Thomas'), subject=Subject('Sending with SendGrid is Fun'), plain_text_content=PlainTextContent('and easy to do anywhere, even with Python'), html_content=HtmlContent('<strong>and easy to do anywhere, even with Python</strong>')) try: print(json.dumps(message.get(), sort_keys=True, indent=4)) sendgrid_client = SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) response = sendgrid_client.send(message=message) print(response.status_code) print(response.body) print(response.headers) except SendGridException as e: print(e.message) # Send a Single Email to Multiple Recipients import os import json from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent, HtmlContent, SendGridException to_emails = [ To('*****@*****.**', 'Elmer SendGrid'), To('*****@*****.**', 'Elmer Thomas')
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()
def test_kitchenSink(self): self.maxDiff = None """All settings set""" mail = Mail() mail.from_email = Email("*****@*****.**", "Example User") mail.subject = "Hello World from the SendGrid Python Library" personalization = Personalization() personalization.add_to(Email("*****@*****.**", "Example User")) personalization.add_to(Email("*****@*****.**", "Example User")) personalization.add_cc(Email("*****@*****.**", "Example User")) personalization.add_cc(Email("*****@*****.**", "Example User")) personalization.add_bcc(Email("*****@*****.**")) personalization.add_bcc(Email("*****@*****.**")) personalization.subject = "Hello World from the Personalized SendGrid Python Library" personalization.add_header(Header("X-Test", "test")) personalization.add_header(Header("X-Mock", "true")) personalization.add_substitution( Substitution("%name%", "Example User")) personalization.add_substitution(Substitution("%city%", "Denver")) personalization.add_custom_arg(CustomArg("user_id", "343")) personalization.add_custom_arg(CustomArg("type", "marketing")) personalization.send_at = 1443636843 mail.add_personalization(personalization) personalization2 = Personalization() personalization2.add_to(Email("*****@*****.**", "Example User")) personalization2.add_to(Email("*****@*****.**", "Example User")) personalization2.add_cc(Email("*****@*****.**", "Example User")) personalization2.add_cc(Email("*****@*****.**", "Example User")) personalization2.add_bcc(Email("*****@*****.**")) personalization2.add_bcc(Email("*****@*****.**")) personalization2.subject = "Hello World from the Personalized SendGrid Python Library" personalization2.add_header(Header("X-Test", "test")) personalization2.add_header(Header("X-Mock", "true")) personalization2.add_substitution( Substitution("%name%", "Example User")) personalization2.add_substitution(Substitution("%city%", "Denver")) personalization2.add_custom_arg(CustomArg("user_id", "343")) personalization2.add_custom_arg(CustomArg("type", "marketing")) personalization2.send_at = 1443636843 mail.add_personalization(personalization2) mail.add_content(Content("text/plain", "some text here")) mail.add_content( Content( "text/html", "<html><body>some text here</body></html>")) attachment = Attachment() attachment.content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12" attachment.type = "application/pdf" attachment.filename = "balance_001.pdf" attachment.disposition = "attachment" attachment.content_id = "Balance Sheet" mail.add_attachment(attachment) attachment2 = Attachment() attachment2.content = "BwdW" attachment2.type = "image/png" attachment2.filename = "banner.png" attachment2.disposition = "inline" attachment2.content_id = "Banner" mail.add_attachment(attachment2) mail.template_id = "13b8f94f-bcae-4ec6-b752-70d6cb59f932" mail.add_section( Section( "%section1%", "Substitution Text for Section 1")) mail.add_section( Section( "%section2%", "Substitution Text for Section 2")) mail.add_header(Header("X-Test1", "test1")) mail.add_header(Header("X-Test3", "test2")) mail.add_header({"X-Test4": "test4"}) mail.add_category(Category("May")) mail.add_category(Category("2016")) mail.add_custom_arg(CustomArg("campaign", "welcome")) mail.add_custom_arg(CustomArg("weekday", "morning")) mail.send_at = 1443636842 mail.batch_id = "sendgrid_batch_id" mail.asm = ASM(99, [4, 5, 6, 7, 8]) mail.ip_pool_name = "24" mail_settings = MailSettings() mail_settings.bcc_settings = BCCSettings( True, Email("*****@*****.**")) mail_settings.bypass_list_management = BypassListManagement(True) mail_settings.footer_settings = FooterSettings( True, "Footer Text", "<html><body>Footer Text</body></html>") mail_settings.sandbox_mode = SandBoxMode(True) mail_settings.spam_check = SpamCheck( True, 1, "https://spamcatcher.sendgrid.com") mail.mail_settings = mail_settings tracking_settings = TrackingSettings() tracking_settings.click_tracking = ClickTracking( True, True) tracking_settings.open_tracking = OpenTracking( True, "Optional tag to replace with the open image in the body of the message") tracking_settings.subscription_tracking = SubscriptionTracking( True, "text to insert into the text/plain portion of the message", "<html><body>html to insert into the text/html portion of the message</body></html>", "Optional tag to replace with the open image in the body of the message") tracking_settings.ganalytics = Ganalytics( True, "some source", "some medium", "some term", "some content", "some campaign") mail.tracking_settings = tracking_settings mail.reply_to = Email("*****@*****.**") expected_result = { "asm": { "group_id": 99, "groups_to_display": [4, 5, 6, 7, 8] }, "attachments": [ { "content": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3" "RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", "content_id": "Balance Sheet", "disposition": "attachment", "filename": "balance_001.pdf", "type": "application/pdf" }, { "content": "BwdW", "content_id": "Banner", "disposition": "inline", "filename": "banner.png", "type": "image/png" } ], "batch_id": "sendgrid_batch_id", "categories": [ "May", "2016" ], "content": [ { "type": "text/plain", "value": "some text here" }, { "type": "text/html", "value": "<html><body>some text here</body></html>" } ], "custom_args": { "campaign": "welcome", "weekday": "morning" }, "from": { "email": "*****@*****.**", "name": "Example User" }, "headers": { "X-Test1": "test1", "X-Test3": "test2", "X-Test4": "test4" }, "ip_pool_name": "24", "mail_settings": { "bcc": { "email": "*****@*****.**", "enable": True }, "bypass_list_management": { "enable": True }, "footer": { "enable": True, "html": "<html><body>Footer Text</body></html>", "text": "Footer Text" }, "sandbox_mode": { "enable": True }, "spam_check": { "enable": True, "post_to_url": "https://spamcatcher.sendgrid.com", "threshold": 1 } }, "personalizations": [ { "bcc": [ { "email": "*****@*****.**" }, { "email": "*****@*****.**" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ], "custom_args": { "type": "marketing", "user_id": "343" }, "headers": { "X-Mock": "true", "X-Test": "test" }, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid " "Python Library", "substitutions": { "%city%": "Denver", "%name%": "Example User" }, "to": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ] }, { "bcc": [ { "email": "*****@*****.**" }, { "email": "*****@*****.**" } ], "cc": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ], "custom_args": { "type": "marketing", "user_id": "343" }, "headers": { "X-Mock": "true", "X-Test": "test" }, "send_at": 1443636843, "subject": "Hello World from the Personalized SendGrid " "Python Library", "substitutions": { "%city%": "Denver", "%name%": "Example User" }, "to": [ { "email": "*****@*****.**", "name": "Example User" }, { "email": "*****@*****.**", "name": "Example User" } ] } ], "reply_to": { "email": "*****@*****.**" }, "sections": { "%section1%": "Substitution Text for Section 1", "%section2%": "Substitution Text for Section 2" }, "send_at": 1443636842, "subject": "Hello World from the SendGrid Python Library", "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932", "tracking_settings": { "click_tracking": { "enable": True, "enable_text": True }, "ganalytics": { "enable": True, "utm_campaign": "some campaign", "utm_content": "some content", "utm_medium": "some medium", "utm_source": "some source", "utm_term": "some term" }, "open_tracking": { "enable": True, "substitution_tag": "Optional tag to replace with the " "open image in the body of the message" }, "subscription_tracking": { "enable": True, "html": "<html><body>html to insert into the text/html " "portion of the message</body></html>", "substitution_tag": "Optional tag to replace with the open" " image in the body of the message", "text": "text to insert into the text/plain portion of" " the message" } } } self.assertEqual( json.dumps(mail.get(), sort_keys=True), json.dumps(expected_result, sort_keys=True) )