def test_smtpapi_add_to(self): """Test that message.to gets a dummy address for the header to work""" m = Mail() m.smtpapi.add_to("*****@*****.**") m.set_from("*****@*****.**") m.set_subject("test") url = self.sg._build_body(m) url.pop("api_key", None) url.pop("api_user", None) url.pop("date", None) test_url = json.loads( """ { "to[]": ["*****@*****.**"], "subject": "test", "from": "*****@*****.**" } """ ) test_url["x-smtpapi"] = json.dumps( json.loads( """ { "to": ["*****@*****.**"] } """ ) ) self.assertEqual(url, test_url)
def publish_diff(self, diff, feed_config): if diff.emailed: raise AlreadyEmailedError(diff.id) elif not (diff.old.archive_url and diff.new.archive_url): raise SendgridArchiveUrlNotFoundError() api_token = feed_config.get("api_token", self.api_token) sender = feed_config.get("sender", self.sender) recipients = None if feed_config.get("recipients"): recipients = self.build_recipients(feed_config.get("recipients")) else: recipients = self.recipients if not all([api_token, sender, recipients]): raise SendgridConfigNotFoundError subject = self.build_subject(diff) message = Mail( from_email=sender, subject=subject, to_emails=recipients.pop(0), html_content=self.build_html_body(diff), ) if recipients: message.bcc = recipients try: self.mailer(api_token).send(message) diff.emailed = datetime.utcnow() logging.info("emailed %s", subject) diff.save() except Exception as e: logging.error("unable to email: %s", e)
def send_email(report, title): API_KEY = os.environ.get('SENDGRID_KEY') if API_KEY is None: print 'No SendGrid API key found! Please set the SENDGRID_KEY env var' sys.exit(1) sg = SendGridClient(API_KEY, raise_errors=True) # Backwards compatability for emails stored as strings, not lists emails = report['project_details']['email'] if type(emails) is not list: emails = [emails] for address in emails: message = Mail() message.add_to(address) message.set_subject(title) message.set_html(generate_email_text(report)) message.set_from('STACKS <*****@*****.**>') try: sg.send(message) except SendGridError as e: print e except SendGridClientError as e: print e except SendGridServerError as e: print e
def index(self): if request.method == 'GET': user_emails = db.session.query(User).filter( User.new_features_subscription == True) email_list = [] for user in user_emails: email_list.append(user.email) email_list.append(';') context = {'user_emails': email_list} return self.render('sendemail.html', **context) else: jsondata = request.get_json(force=True) users_send_email_to = db.session.query(User).filter( User.new_features_subscription == True) message = Mail() message.set_subject(jsondata['subject'].encode("utf8")) message.set_text(jsondata['message'].encode("utf8")) message.set_from('ANYWAY Team <*****@*****.**>') for user in users_send_email_to: message.add_bcc(user.email) try: sg.send(message) except SendGridClientError: return "Error occurred while trying to send the emails" except SendGridServerError: return "Error occurred while trying to send the emails" return "Email/s Sent"
def welcome_email(user): message = Mail(from_email=from_email, to_emails=user.email) message.template_id = 'd-a97bb89a6bfe44fda4deba762ef6a424' message.dynamic_template_data = { 'name': user.first_name, 'url': base_url + '/confirm-email?token=' + user.email_verification_token } sg.send(message)
def forgot_password(user): message = Mail(from_email=os.environ.get('FROM_EMAIL'), to_emails=user.email) message.template_id = 'd-f626293dd98649d6b6d53a5aa3a355d4' message.dynamic_template_data = { 'name': user.first_name, 'url': base_url + '/reset-password?token=' + user.password_reset_token } sg.send(message)
def send_invite_member(from_user, to_email, token, message_text): message = Mail(from_email=os.environ.get('FROM_EMAIL'), to_emails=to_email) message.template_id = 'd-d1fc8d063c1c464792606f70fe6acfbf' message.dynamic_template_data = { 'inviter_name': from_user.first_name, 'message': message_text, 'url': 'http://localhost:3000/invitation?token=' + token } sg.send(message)
def send_message_with_sg(send_to, send_from, subject, body): message = Mail() message.add_to(send_to) message.set_from(send_from) message.set_subject(subject) message.set_html(body) print "Sending email:({}) to :({})".format(subject, send_to) sg.send(message)
def send(self): mail = Mail( from_email=self.from_email, to_emails=self.to_email, subject=self.title, html_content=self.content, ) response = self.send_grid.client.mail.send.post( request_body=mail.get())
def index(self): if request.method=='GET': user_emails = db_session.query(User).filter(User.new_features_subscription == True) email_list = [] for user in user_emails: email_list.append(user.email) email_list.append(';') context = {'user_emails': email_list} return self.render('sendemail.html', **context) else: jsondata = request.get_json(force=True) users_send_email_to = db_session.query(User).filter(User.new_features_subscription == True) message = Mail() message.set_subject(jsondata['subject'].encode("utf8")) message.set_text(jsondata['message'].encode("utf8")) message.set_from('ANYWAY Team <*****@*****.**>') for user in users_send_email_to: message.add_bcc(user.email) try: status, msg = sg.send(message) except SendGridClientError: return "Error occurred while trying to send the emails" except SendGridServerError: return "Error occurred while trying to send the emails" return "Email/s Sent"
def new_user_email_notify(user, password): print("sending password to ") print(user.email) message = Mail(from_email='[email protected]', to_emails=user.email, subject='new user', html_content='<strong></strong>') message.dynamic_template_data = {"email": user.email, "password": password} message.template_id = NEW_USER_TEMPLATE_ID sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY) sendgrid_client.send(message)
def send(self, to_email=None, subject=None, content=None, content_type=None): from_email = Email(self.from_email) to_email = To(to_email) content = Content(content_type, content) mail = Mail(from_email, to_email, subject, content) return self.sendgrid_client.client.mail.send.post( request_body=mail.get())
def send_email(name: str, address: str, subject: str, template: str, values: dict) -> bool: sg = SendGridClient(config.SENDGRID_API_USER, config.SENDGRID_API_KEY) mail = Mail() mail.set_from('tototo <*****@*****.**>') mail.add_to(name + ' <' + address + '>') mail.set_subject(subject) mail.set_html(render_template(template, **values)) status, _ = sg.send(mail) return status == 200
def recieve_result(): account_sid = "ACe36f8844f05de80021faa460764b6d33" auth_token = "f22d67391209d2a4f8f54266cd721978" client = TwilioRestClient(account_sid, auth_token) global numberTwo value = request.form fromValue = value.get("From") bodyValue = value.get("Body") toValue = value.get("To") # print "Body: " + bodyValue # print "From: " + fromValue # print "To: " + toValue value = "True" if str(bodyValue) == "An outage was reported in your area. We expect this to be resolved by 6pm today.": value = "False" elif str(bodyValue).strip().lower() == "yes": value = "yes" if value == "True": htmlForEmail = '<html><body><img src="http://wedte.com/wp-content/uploads/2013/01/PowerOutage.jpg" alt="Power Outage"><p></p><p></p><h3> We think that your house may have a power outage. If this is true, simply reply to this e-mail with any response so that the Electricty Supplier can serve you faster. <p></p><br><br></h3></body></html>' sg = SendGridClient(SendGridUserName, SendGridPassword) message = Mail() message.add_to(emailValue) message.set_subject("Is there a Power Outage at your house?") message.set_html(htmlForEmail) message.set_from(FromEmail) status, msg = sg.send(message) message = client.messages.create( body="We think that your house may have a power outage. If this is true, simply reply to this text with a 'yes' so that the Electricty Supplier can serve you faster.", to=str(personalNumber), # Replace with your phone number from_=str(number), ) # Replace with your Twilio number elif value == "yes": value = "True" elif value == "no": value = "False" payload = {"powerOutage": value, "twilioNumber": number} r = requests.post("http://ec2-54-68-73-74.us-west-2.compute.amazonaws.com:5000/powerreply", data=payload) numberTwo = number print str(value) print numberTwo return "Test"
def _send_message_with_sg(send_to, send_from, subject, body): message = Mail() message.add_to(send_to) message.set_from(send_from) message.set_subject(subject) message.set_html(body) print "Sending email:({}) to :({})".format(subject, send_to) sg.send(message)
def get_sendgrid_request_message(cfg, keyid, hex, user_email): url_prefix = urljoin(cfg.config.megserver_hostname_url, os.path.join(cfg.config.meg_url_prefix, "revoke")) params = urlencode([("keyid", keyid), ("token", hex)]) parsed = list(urlparse(url_prefix)) parsed[4] = params revocation_link = urlunparse(parsed) message = Mail() message.add_to(user_email) message.set_from(cfg.config.sendgrid.from_email) message.set_subject(cfg.config.sendgrid.subject) message.set_html(EMAIL_HTML.format(keyid=keyid, link=revocation_link)) return message
def send_mail_async(sender: str, receivers, subject, dynamic_template_data: dict, template_id): message = Mail( from_email=sender, to_emails=receivers, subject=subject, ) message.dynamic_template_data = dynamic_template_data message.template_id = template_id sg = SendGridAPIClient(settings.SENDGRID_API_KEY) t = threading.Thread(target=sg.send, args=(message, ), name=f'email to {receivers}') t.setDaemon(True) t.start()
def _send_eos(results, run_time): subject = '[DNStats] Scan Ending' print("taco") print(run_time) result_count = db_session.query( models.SiteRun).filter_by(run_id=run_time).count() print("result_count: " + str(result_count)) body = ''' End time: {starting_time} Number results: {result_count} Run id: {run_id} DNStats scan has ended. '''.format(starting_time=datetime.datetime.now().strftime('%c'), result_count=result_count, run_id=run_time) message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=subject, plain_text_content=body) _send_message(message) print("body: " + body)
def _send_botched_deploy(date, run_id: int, count: int, target_count: int) -> None: """ Send a email stating not enough sites have been scanned :param date: start date of the scan :param run_id: database id of the scan :param count: number of sites that have been complted in the scan :param target_count: the target number of scans, below this numbet the deployment will be refused :return: None """ delta = target_count - count subject = '[DNStats] CRITICAL Botched Website Deploy' body = ''' Run id: {run_id} Target: {target_count} Actual = {count} Delta = {delta} Run start Time = {starting_time} Cowardly refusing to deploy run {run_id}, it appears the scan failed or is not finished. Investigate and publish results. '''.format(starting_time=date.strftime('%c'), run_id=run_id, target_count=target_count, count=count, delta=delta) message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=subject, plain_text_content=body) _send_message(message)
def send_email(email_params): if is_local(): # localhost (not really sending the email) print("***********************") print( "You are on localhost, so no e-mail will be sent. This is message:" ) print(email_params["message_body"]) print("+++++++++++++++++++++++") else: # production (sending the email via SendGrid) # SendGrid setup sg = SendGridAPIClient(api_key=os.getenv("SendGrid-Mail")) # E-mail setup sender_email = os.getenv("APP_EMAIL") recipient = email_params["recipient_email"] subject = email_params["message_title"] msg_html = email_params["message_html"] email_message = Mail(from_email=sender_email, to_emails=recipient, subject=subject, html_content=msg_html) try: response = sg.send(email_message) logging.info(response.status_code) logging.info(response.body) logging.info(response.headers) except Exception as e: logging.error(str(e))
def post(self, request, *args, **kwargs): print(request.POST) # create the user ticket user_obj = Profile.objects.get(user=request.user) company_obj = Company.objects.get( name__iexact=request.POST.get("company")) SupportTickets.objects.create( user=user_obj, title=request.POST.get("title"), content=request.POST.get("message"), ticket_id=random_string_generator(7), affected_company=company_obj, slug=random_string_generator(20), ) # send mail to system core.. sg = SendGridAPIClient(email_settings.SENDGRID_API_KEY) message = Mail( from_email=email_settings.DEFAULT_FROM_EMAIL, to_emails=email_settings.SUPPORT_EMAIL, subject="A New Ticket Was Opened!", html_content= "A support ticket has been opened please confirm and attend to all opened tickets." ) sg.send(message) return JsonResponse({"message": "Ticket Created Successfully!"})
def forgot_password(): if request.method == 'POST': email = request.form['email'] user = Account.query.filter_by(email=email).first() print(user.hash_email) if user is not None: # send an email link = "http://127.0.0.1:5000/reset/" + user.hash_email message = Mail( from_email='*****@*****.**', to_emails=[email], subject="Password Reset", html_content= "This is your link to reset your password (copy and paste whole link): " + link) # reset/hashed email for security sg.send(message) return redirect( url_for( 'success', message= "Success! An email of confirmation has been sent to you. " "Click on the link attached to change your password.")) return render_template('forgot.html')
def __init__(self): self.email_config = SendGridConfiguration.objects.all()[:1].get() self.sg = SendGridClient(self.email_config.api_key) self.message = Mail() self.message.set_from(self.email_config.email_from) self.message.set_from_name(self.email_config.email_from_name) self.message.set_subject(self.email_config.email_subject)
def email_sender(sender, instance, **kwargs): Email_subscribers = EmailSubscribers.objects.all() msg = Emails.objects.latest('email') ms = msg.email for email_subscriber in Email_subscribers: email = email_subscriber.email message = Mail( from_email='*****@*****.**', to_emails=email, subject='Newsletter subscription', html_content=ms, ) 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('not working')
def contactMap(request): successMail = False recaptchaFailed = False recaptch = False # find the settings linked with user # if no linked settings item exist if request.method == 'GET': # if user is logged in, fields are automatically filled in. if not request.user.is_authenticated: form = ContactFormNotLogin() recaptch = True else: form = ContactForm(request.user) else: # post function executed when the user clicks send. if not request.user.is_authenticated: recaptch = True form = ContactFormNotLogin(request.POST) #Recaptcha check for users that are not logged in recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': recaptcha_response } r = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if not result['success']: recaptchaFailed = True else: form = ContactForm(request.user, request.POST) if form.is_valid(): #when all mandatory fields have been filled out subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = { 'first_Name': form.cleaned_data['firstName'], 'name': form.cleaned_data['lastName'], 'subject': form.cleaned_data['subject'], 'text': form.cleaned_data['message'], 'tel': form.cleaned_data['phone'], 'mail': form.cleaned_data['from_email'] } #collects information from the form to pass to email htmlcontend = get_template('emailTamplate.html').render( message) #formats/creates email message = Mail(from_email='*****@*****.**', to_emails=settings.CONTACT_RECEIVERS, subject=subject, html_content=htmlcontend) sg = SendGridAPIClient(settings.EMAIL_HOST_PASSWORD) response = sg.send(message) successMail = True return render( request, 'mapContact.html', { 'form': form, "recaptcha": recaptch, 'successMail': successMail, 'recaptchaFailed': recaptchaFailed })
def send_activation_email(data): message = Mail(from_email=EMAIL_SENDER, to_emails=data['to_email'], subject=data['subject'], html_content=data['message']) sg = SendGridAPIClient(SENDGRID_KEY) sg.send(message)
def send_email(routes_to_report): """Send email using sendgrid.""" number_of_routes = len(routes_to_report) if number_of_routes == 0: return False formatted_date = dt.datetime.utcnow().strftime("%A, %b %d") rich_email_body = render_template("email.html", routes=routes_to_report, date=formatted_date) sg = SendGridClient(config.SG_USERNAME, config.SG_PASSWORD, raise_errors=True) formatted_time = dt.datetime.utcnow().strftime("%F %T") subject = '({}): {} routes' subject = subject.format(formatted_time, number_of_routes) try: message = Mail(to=config.TO_EMAIL, subject=subject, html=rich_email_body, from_email=config.FROM_EMAIL) status, msg = sg.send(message) return msg except SendGridClientError as e: print 'Failed to send email: ', e raise
def send(**kwargs): print('sending message') print(_green(kwargs)) result = True body = Content( "text/html", loader.render_to_string(kwargs.get('email_template'), kwargs.get('context'))) try: message = Mail(from_email=settings.SENGRID_SENDER_EMAIL, to_emails=kwargs.get('to_email'), subject=kwargs.get('subject'), html_content=body) sengrid_email = SendGridAPIClient(api_key=settings.SENDGRID_API_KEY) email_request = sengrid_email.send(message) print(_green('----------- sendgrid email response -----------')) print(email_request.status_code) print(email_request.body) print(email_request.headers) print(_green('----------- sendgrid email response -----------')) except Exception as e: result = False if not settings.DEBUG: slack_messages.run( msg='Error sending email to {} : Error: {}'.format( kwargs.get('to_email'), str(e)), channel_id=settings.SLACK_BUGS_CHANNEL_ID) print(_red('Error sending email caused by : {}'.format(str(e)))) return result
def send_informing_about_comment_email(news_author_id, comment_author_id, news_id, domain): UserModel = get_user_model() try: news_author = UserModel.objects.get(pk=news_author_id) comment_author = UserModel.objects.get(pk=comment_author_id) message = render_to_string( 'informing_about_comment_mail.html', { 'news_author': news_author, 'comment_author': comment_author, 'domain': domain, 'news_id': news_id }) message = Mail( from_email='*****@*****.**', to_emails=news_author.email, subject='К вашемей новости на сайте {} оставлен комментарий'. format(domain), html_content=message) sg = SendGridAPIClient(SEND_GRID_API_KEY) sg.send(message) except UserModel.DoesNotExist: pass except Exception as e: print(e)
def email_twets(email): mail = Mail(from_email='*****@*****.**', to=email, subject='Tweets', text=str(list(tweets.find()))) sg.send(mail) return jsonify({})
def perform(self, message: AbstractMessage, sender: str, lang: str, **kwargs): context = self.get_context_data(message) title_html, body_html = self.render(message, lang, context) attachments = self.get_attachments(message, lang, context) sendgrid_message = Mail( from_email=self.get_sender(), to_emails=message.recipient, subject=title_html, html_content=body_html, ) for attachment in attachments: sendgrid_message.add_attachment(attachment) # sendgrid_message.add_attachment(self.get_logo_attachment()) # must be removed to the child class for the library version response = self.client.send(sendgrid_message) return response
def send_message(self, message='', **kwargs): subject = kwargs.get(ATTR_TITLE) from sendgrid import Mail mail = Mail(from_email=self.sender, to=self.recipient, html=message, text=message, subject=subject) self._sg.send(mail)
def sendgrid_email(email, name): body = 'Hi,' + name message = Mail(from_email='*****@*****.**', to_emails=email, subject=SUBJECT, plain_text_content=body) response = sg.send(message)
def send_email(email, code): body = "my code =" + code message = Mail(from_email="*****@*****.**", to_emails=email, subject=subject, plain_text_content=body) print(email, code) response = sg.send(message)
def send_email(email,code): body = 'best code='+code message = Mail( from_email='*****@*****.**', to_emails=email, subject=SUBJECT, plain_text_content=body, ) response = sg.send(message)
def get_sendgrid_request_message(cfg, keyid, hex, user_email): url_prefix = urljoin( cfg.config.megserver_hostname_url, os.path.join(cfg.config.meg_url_prefix, "revoke") ) params = urlencode([("keyid", keyid), ("token", hex)]) parsed = list(urlparse(url_prefix)) parsed[4] = params revocation_link = urlunparse(parsed) message = Mail() message.add_to(user_email) message.set_from(cfg.config.sendgrid.from_email) message.set_subject(cfg.config.sendgrid.subject) message.set_html(EMAIL_HTML.format(keyid=keyid, link=revocation_link)) return message
def post(self): application_key = ndb.Key(urlsafe=self.request.get('form-key')) application = application_key.get() not_complete = self._not_complete() if True in not_complete.values(): # If there is an error self.response.set_status(204) self._serve_page(errors=self._not_complete()) else: applicant = self.user application.submit_time = datetime.now() application.put() config = ndb.Key(Settings, 'config').get() sg = SendGridClient(config.sendgrid_username, config.sendgrid_password, secure=True) verification_email = Mail(from_name="NYDKC Awards Committee", from_email="*****@*****.**", subject="DKC Application Confirmation for %s %s" % (applicant.first_name, applicant.last_name), to=applicant.email ) template_values = { 'applicant': applicant, 'application': application } verification_email.set_html(JINJA_ENVIRONMENT.get_template('confirmation-email.html').render(template_values)) htmlhandler = html2text.HTML2Text() verification_email.set_text(htmlhandler.handle(verification_email.html).encode("UTF+8")) code, response = sg.send(verification_email) response = json.loads(response) if response["message"] == "error": logging.error(("Problem with sending email to %s: " % verification_email.to) + str(response["errors"])) self._serve_page() return self.redirect('/application')
def test_smtpapi_add_to(self): '''Test that message.to gets a dummy address for the header to work''' m = Mail() m.smtpapi.add_to('*****@*****.**') m.set_from('*****@*****.**') m.set_subject('test') url = self.sg._build_body(m) url.pop('api_key', None) url.pop('api_user', None) url.pop('date', None) test_url = json.loads(''' { "to[]": ["*****@*****.**"], "subject": "test", "from": "*****@*****.**" } ''') test_url['x-smtpapi'] = json.dumps(json.loads(''' { "to": ["*****@*****.**"] } ''')) self.assertEqual(url, test_url)
def test_send(self): m = Mail() m.add_to('John, Doe <*****@*****.**>') m.set_subject('test') m.set_html('WIN') m.set_text('WIN') m.set_from('*****@*****.**') m.add_substitution('subKey', 'subValue') m.add_section('testSection', 'sectionValue') m.add_category('testCategory') m.add_unique_arg('testUnique', 'uniqueValue') m.add_filter('testFilter', 'filter', 'filterValue') m.add_attachment_stream('testFile', 'fileValue') self.sg.send(m) url = self.sg._build_body(m) url.pop('api_key', None) url.pop('api_user', None) url.pop('date', None) testUrl = json.loads('''{"to[]": ["*****@*****.**"], "toname[]": ["John Doe"], "html": "WIN", "text": "WIN", "subject": "test", "files[testFile]": "fileValue", "from": "*****@*****.**", "headers": "", "fromname": "", "replyto": ""}''') testUrl['x-smtpapi'] = json.dumps(json.loads('''{"sub":{"subKey":["subValue"]}, "section":{"testSection":"sectionValue"}, "category":["testCategory"], "unique_args":{"testUnique":"uniqueValue"}, "filters":{"testFilter":{"settings":{"filter":"filterValue"}}}}''')) self.assertEqual(url, testUrl)
def test__build_body_unicode(self): """test _build_body() handles encoded unicode outside ascii range""" from_email = '\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]' from_name = '\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f' subject = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0' text = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0' html = '\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0' reply_to = '\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]' m = Mail() m.add_to('John, Doe <*****@*****.**>') m.set_subject(subject) m.set_html(html) m.set_text(text) m.set_from("%s <%s>" % (from_name, from_email)) url = self.sg._build_body(m) self.assertEqual(from_email, url['from']) self.assertEqual(from_name, url['fromname']) self.assertEqual(subject, url['subject']) self.assertEqual(text, url['text']) self.assertEqual(html, url['html'])
def test_send(self): m = Mail() m.add_to("John, Doe <*****@*****.**>") m.set_subject("test") m.set_html("WIN") m.set_text("WIN") m.set_from("*****@*****.**") m.set_asm_group_id(42) m.add_cc("*****@*****.**") m.add_bcc("*****@*****.**") m.add_substitution("subKey", "subValue") m.add_section("testSection", "sectionValue") m.add_category("testCategory") m.add_unique_arg("testUnique", "uniqueValue") m.add_filter("testFilter", "filter", "filterValue") m.add_attachment_stream("testFile", "fileValue") url = self.sg._build_body(m) url.pop("api_key", None) url.pop("api_user", None) url.pop("date", None) test_url = json.loads( """ { "to[]": ["*****@*****.**"], "toname[]": ["John Doe"], "html": "WIN", "text": "WIN", "subject": "test", "files[testFile]": "fileValue", "from": "*****@*****.**", "cc[]": ["*****@*****.**"], "bcc[]": ["*****@*****.**"] } """ ) test_url["x-smtpapi"] = json.dumps( json.loads( """ { "sub": { "subKey": ["subValue"] }, "section": { "testSection":"sectionValue" }, "category": ["testCategory"], "unique_args": { "testUnique":"uniqueValue" }, "filters": { "testFilter": { "settings": { "filter": "filterValue" } } }, "asm_group_id": 42 } """ ) ) self.assertEqual(url, test_url)
def test_send(self): m = Mail() m.add_to('John, Doe <*****@*****.**>') m.set_subject('test') m.set_html('WIN') m.set_text('WIN') m.set_from('*****@*****.**') m.set_asm_group_id(42) m.add_cc('*****@*****.**') m.add_bcc('*****@*****.**') m.add_substitution('subKey', 'subValue') m.add_section('testSection', 'sectionValue') m.add_category('testCategory') m.add_unique_arg('testUnique', 'uniqueValue') m.add_filter('testFilter', 'filter', 'filterValue') m.add_attachment_stream('testFile', 'fileValue') url = self.sg._build_body(m) url.pop('api_key', None) url.pop('api_user', None) url.pop('date', None) test_url = json.loads(''' { "to[]": ["*****@*****.**"], "toname[]": ["John Doe"], "html": "WIN", "text": "WIN", "subject": "test", "files[testFile]": "fileValue", "from": "*****@*****.**", "cc[]": ["*****@*****.**"], "bcc[]": ["*****@*****.**"] } ''') test_url['x-smtpapi'] = json.dumps(json.loads(''' { "sub": { "subKey": ["subValue"] }, "section": { "testSection":"sectionValue" }, "category": ["testCategory"], "unique_args": { "testUnique":"uniqueValue" }, "filters": { "testFilter": { "settings": { "filter": "filterValue" } } }, "asm_group_id": 42 } ''')) try: self.assertItemsEqual(url, test_url) except: # Python 3+ self.assertCountEqual(url, test_url)
def charge(): """ Charge this user, and take their moneys! """ # By default, the following is true: # - All investments are 20$. # - The default lower limit is 50%. # - The default upper limit is 50%. amount = 100 #lower_limit = int(request.form.get('lower-limit')) or 50 #upper_limit = int(request.form.get('upper-limit')) or 50 lower_limit = 50 upper_limit = 50 id = uuid4().hex # Create a Strip customer. customer = stripe.Customer.create( email = user.email, card = request.form['stripeToken'], ) # Bill the user. stripe.Charge.create( customer = customer.id, amount = amount, currency = 'usd', description = 'BitRich Investment', ) # Get current exchange rates: resp = get('https://coinbase.com/api/v1/currencies/exchange_rates') rate = float(resp.json()['usd_to_btc']) resp = post( 'https://coinbase.com/api/v1/buys?api_key=%s' % app.config['COINBASE_API_KEY'], headers = { 'Content-Type': 'application/json', }, data = dumps({'qty': rate * (amount / 100)}), ) # Store investment details in Stormpath. try: user.custom_data['investments'].append({ 'id': id, 'created': datetime.utcnow().isoformat(), 'updated': datetime.utcnow().isoformat(), 'deposit_amount_usd': amount, 'deposit_amount_bitcoin': float(resp.json()['transfer']['btc']['amount']), 'lower_limit': lower_limit, 'upper_limit': upper_limit, }) except: user.custom_data['investments'] = [] user.custom_data['investments'].append({ 'id': id, 'created': datetime.utcnow().isoformat(), 'updated': datetime.utcnow().isoformat(), 'deposit_amount_usd': amount, 'deposit_amount_bitcoin': float(resp.json()['transfer']['btc']['amount']), 'lower_limit': lower_limit, 'upper_limit': upper_limit, }) user.save() message = Mail( to = user.email, subject = 'Thanks for your Investment!', text = '', from_email = '*****@*****.**', ) message.set_html(render_template( 'email/deposit_email.html', user = user, ).encode('utf_8').decode('unicode_escape')) sendgrid.send(message) return redirect(url_for('dashboard'))
def send_activation_mail(self): message = Mail() message.add_to(self.info['email']) message.set_subject('UthPortal activation') address = self.info['email'] token = self.info['token'] auth_id = self.info['auth_id'] self.logger.debug('domain: ' + self._domain) #TODO: make some proper html message.set_html( "Please click on the following link to activate your account:\ <a href={0}/api/v1/users/activate?email={1}&token={2}>Activate</a>, \ This is your 8-digit unique user id: {3}\ Use this in your app, when asked for it.\ This id is used to personalize your push notifications.\ Please don't share this ID as it is supposed to be kept secret."\ .format(self._domain, address, token, auth_id)) message.set_text('Token: {0}, 8-digit: {1}'.format(token, auth_id)) message.set_from('UthPortal <%s>' % self._email_from) try: self._sg.send(message) except SendGridError as error: self.logger.error('SendGrid error: ' + str(error)) raise NetworkError("Cannot send activation-email.", 500) except SendGridClientError as error: self.logger.error('SendGrid CLIENT error: ' + error.args[1]) raise NetworkError('Cannot send activation e-mail.', 500) except SendGridServerError as error: self.logger.error('SendGrid SERVER error: [{0}] -> [{1}] ',format( error.args[0], error.args[1] )) raise NetworkError('Mail server currently un-available', 503)
def test_drop_to_header(self): m = Mail() m.add_to('John, Doe <*****@*****.**>') m.set_from('*****@*****.**') m.set_subject('test') m.set_text('test') m.add_bcc('John, Doe <*****@*****.**>') url = self.sg._build_body(m) print url
def send_email(subject='Test email', from_email='*****@*****.**', from_name='D. Goodwin', recipients=['*****@*****.**'], text_body='Hello from Flask', html_body='Hello from <b>Flask</b>'): from sendgrid import SendGridClient, Mail api_key = 'm3tr0pl4c3s' api_user = '******' sendgrid = SendGridClient(username=api_user, password=api_key, raise_errors=True, host='http://api.sendgrid.com', port=80, ) message = Mail() message.add_to(recipients) message.set_from(from_email) message.set_from_name(from_name) message.set_subject(subject) message.set_text(text_body) message.set_html(html_body) try: sendgrid.send(message) except Exception as e: print "fail: %s" %(e)
def sell_or_not(): resp = get('https://coinbase.com/api/v1/currencies/exchange_rates') rate = float(resp.json()['usd_to_btc']) print 'Checking whether we should sell or not with current BTC rates of:', rate with app.app_context(): for user in app.stormpath_manager.application.accounts: user.__class__ = User print 'Checking user:'******'investments', []): print 'Checking investment:', investment['id'] print 'Lower sell limit is set to: %s%%' % investment['lower_limit'] print 'Upper sell limit is set to: %s%%' % investment['upper_limit'] # Grab the total BTC / USD that this user has in their account # (when the investment was made). total_btc = float(investment['deposit_amount_bitcoin']) total_usd_cents = investment['deposit_amount_usd'] # btc_adjusted is the amount of bitcoin this user's money is # worth at current rates btc_adjusted = total_btc * (total_usd_cents / 100.0) print 'btc_adjusted (old):', btc_adjusted print 'rate (new):', rate # Now that we know how much bitcoin is currently worth, vs what # the user has -- we can calculate the net gain of this user's # investment. differential = float('%.2f' % (((rate - btc_adjusted) / btc_adjusted) * 100)) print 'differential: %s%%' % differential message = Mail( to = user.email, subject = 'BitRich Investment Notification', text = '', from_email = '*****@*****.**', ) if differential < (investment['lower_limit'] * -1): print "We've lost %s%%! Time to sell! Our lower limit is %s%%!" % ( differential, investment['lower_limit'], ) message.set_html(render_template( 'email/lower_sell_email.html', user = user, differential = differential, investment = investment, ).encode('utf_8').decode('unicode_escape')) sendgrid.send(message) investment['upper_limit'] = -.5 if differential > investment['upper_limit']: print "We've made %s%%! Time to sell! Our upper limit is %s%%!" % ( differential, investment['upper_limit'], ) message.set_html(render_template( 'email/upper_sell_email.html', user = user, differential = differential, investment = investment, ).encode('utf_8').decode('unicode_escape')) sendgrid.send(message)
def config_mail(): message = Mail() message.add_to("<*****@*****.**>") message.add_to_name("Kumar, Palani") message.set_from("*****@*****.**") message.set_from_name("Kavin"); message.set_subject("Test message.,") message.set_text("Test text") message.set_html("<i><b>Test HTML</b></i>") message.set_replyto("*****@*****.**") message.set_date(rfc822.formatdate()) return message
def get_template_id_by_name(template_name): response = sg.client.templates.get() data = json.loads(response.response_body.decode()) t_groups = data['templates'] for t_group in t_groups: templates = t_group['versions'] for template in templates: if template['name'] == template_name: return t_group['id'] template_id = get_template_id_by_name(template_name) message = Mail() message.add_filter('templates', 'enable', '1') message.add_filter('templates', 'template_id', template_id) message.set_subject(None) for to_addr in to_addrs: message.add_to(to_addr) for key, value in context.items(): message.add_substitution("%{}%".format(key), value) message.set_from('Foo <*****@*****.**>') message.set_html(' ') message.set_text(' ') message.set_subject(' ')
class EmailClient(object): def __init__(self): self.sg = SendGridClient(SG_API_KEY) self.message = Mail() self.message.set_from(SG_FROM) self.message.set_from_name(SG_FROM_NAME) def send_sg_email(self, correo): # valores de envío self.message.add_to(correo.correo) self.message.add_to_name(correo.nombre_cliente) self.message.set_subject(correo.asunto) self.message.set_html(correo.html) # valores personalizados unique_args = { 'empresa': correo.empresa, 'rut_receptor': correo.rut_receptor, 'rut_emisor': correo.rut_emisor, 'tipo_envio': correo.tipo_envio, 'tipo_dte': correo.tipo_dte, 'numero_folio': correo.numero_folio, 'resolucion_receptor': correo.resolucion_receptor, 'resolucion_emisor': correo.resolucion_emisor, 'monto': correo.monto, 'fecha_emision': correo.fecha_emision, 'fecha_recepcion': correo.fecha_recepcion, 'estado_documento': correo.estado_documento, 'tipo_operacion': correo.tipo_operacion, 'tipo_receptor': correo.tipo_receptor, } self.message.set_unique_args(unique_args) # Validacion de adjuntos if correo.attachs: for adjunto in correo.attachs: adj = AttachModel.query(ancestor=adjunto).get() self.message.add_attachment_stream(adj.nombre, adj.archivo) # enviando el mail status, msg = self.sg.send(self.message) # imprimiendo respuesta logging.info(status) logging.info(msg) def send_mail_to_user_attach(self, correo): # valores de envío self.message.add_to(correo['email']) self.message.add_to_name(correo['user_name']) self.message.set_subject(correo['subject']) self.message.set_html(correo['html']) if correo['attach']: self.message.add_attachment_stream(correo['attach']['name'], correo['attach']['file']) status, msg = self.sg.send(self.message) # imprimiendo respuesta logging.info(status) logging.info(msg)
def test__build_body_unicode(self): """test _build_body() handles encoded unicode outside ascii range""" from_email = "\xd0\x9d\xd0\xb8\xd0\xba\xd0\[email protected]" from_name = "\xd0\x9a\xd0\xbb\xd0\xb0\xd0\xb2\xd0\xb4\xd0\xb8\xd1\x8f" subject = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0" text = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0" html = "\xd0\x9d\xd0\xb0\xd0\xb4\xd0\xb5\xd0\xb6\xd0\xb4\xd0\xb0" m = Mail() m.add_to("John, Doe <*****@*****.**>") m.set_subject(subject) m.set_html(html) m.set_text(text) m.set_from("%s <%s>" % (from_name, from_email)) url = self.sg._build_body(m) self.assertEqual(from_email, url["from"]) self.assertEqual(from_name, url["fromname"]) self.assertEqual(subject, url["subject"]) self.assertEqual(text, url["text"]) self.assertEqual(html, url["html"])
def threshold_not_met(petitioner_id, organization, election, threshold, signatures, position, petition_email, admin_emails): petitioner = netid2name(petitioner_id) # Make a secure connection to SendGrid sg = SendGridClient('harmonica1243', 'xqBrrnNqbGuvtEUpNRs3RePW', secure=True) # Replace with the message that we want to send, such as the name of the person and the position html_petition = '<p style="text-align: left;"><b>Dear ' + petitioner + ',</b></p><p style="text-align: center;">' \ '<p>Your petition no longer has the required number of signatures</p><ul><li><b>Organization:</b> ' \ + organization + '</li><li><b>Election:</b> ' + election + '</li><li><b>Position:</b> ' + position + '</li>' \ '<li><b>Number of Signatures Required:</b> ' + threshold + '</li><li><b>Number of Signatures Obtained:</b> ' \ + signatures + '</li></ul><p>Please contact the organization directly with any questions about the petition.' \ '</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>' html_admin = '<p style="text-align: left;"><b>Dear Organization Administrator,</b></p><p style="text-align: center;">' \ '<p>This petition no longer has the required number of signatures</p><ul><li><b>Petition Creator:</b> ' \ + petitioner + '</li><li><b>Organization:</b> ' + organization + '</li><li><b>Election:</b> ' + election + \ '</li><li><b>Position:</b> ' + position + '</li><li><b>Number of Signatures Required:</b> ' + threshold + \ '</li><li><b>Number of Signatures Obtained:</b> ' + signatures + '</li></ul><p>Please contact ' + ADMIN_ID + \ '@rice.edu with any questions.</p></p><p style="text-align: left;"><b>Rice Apps Petitions</b></p>' # Make a message Object message = Mail() # Message Subject, Body and To message.set_subject('Petition No Longer Has Enough Signatures') message.set_html(html_petition) message.set_from('*****@*****.**') message.add_to('<' + petition_email + '>') sg.send(message) # Make a message Object message = Mail() # Message Subject, Body and To message.set_subject('Petition No Longer Has Enough Signatures') message.set_html(html_admin) message.set_from('*****@*****.**') for email in admin_emails: message.add_to('<' + email + '>') sg.send(message)
class SGEmailClient(object): def __init__(self): self.email_config = SendGridConfiguration.objects.all()[:1].get() self.sg = SendGridClient(self.email_config.api_key) self.message = Mail() self.message.set_from(self.email_config.email_from) self.message.set_from_name(self.email_config.email_from_name) self.message.set_subject(self.email_config.email_subject) def send_report_email(self, email, report): template_config = TemplateReport.objects.all()[:1].get() user = get_object_or_404(User, pk=email) logger.info(user) html = unicode(template_config.html_template).format( user_name=user.first_name, ) self.message.add_to(user.email) self.message.add_to_name(user.first_name) self.message.set_html(html) if report['report']: self.message.add_attachment_stream( report['name'] , report['report'] ) status, msg = self.sg.send(self.message) logger.info('{0} - {1}'.format(status, msg))
def test_drop_to_header(self): smtpapi = "{}" m = Mail() m.add_to("John, Doe <*****@*****.**>") m.set_from("*****@*****.**") m.set_subject("test") m.set_text("test") m.add_bcc("John, Doe <*****@*****.**>") url = self.sg._build_body(m) self.assertEqual(smtpapi, url["x-smtpapi"])
_user = stormpath_manager.application.accounts.create({ 'email': request.form.get('email'), 'password': request.form.get('password'), 'given_name': 'John', 'surname': 'Doe', }) _user.__class__ = User except StormpathError, err: # If something fails, we'll display a user-friendly error message. return render_template('register.html', error=err.message) login_user(_user, remember=True) message = Mail( to = _user.email, subject = 'Welcome to BitRich!', text = '', from_email = '*****@*****.**', ) message.set_html(render_template( 'email/verification_email.html', user = user, ).encode('utf_8').decode('unicode_escape')) sendgrid.send(message) return redirect(url_for('dashboard')) @app.route('/login', methods=['GET', 'POST']) def login(): """ This view logs in a user given an email address and password.
def __init__(self): self.sg = SendGridClient(SG_API_KEY) self.message = Mail() self.message.set_from(SG_FROM) self.message.set_from_name(SG_FROM_NAME)
def post(self): applicant = self.user application_key = ndb.Key(urlsafe=self.request.get('form-key')) application = application_key.get() if self._no_verify() or application.submit_time: logging.info("Attempt to modify verification by %s", applicant.email) self._serve_page() return task = self.request.get('task') if task != 'applicant': user_id = self.user.get_id() token = self.user_model.create_signup_token(user_id) verification_url = self.uri_for('verification', type='v', user_id=user_id, signup_token=token, _full=True) logging.info(verification_url) config = ndb.Key(Settings, 'config').get() sg = SendGridClient(config.sendgrid_username, config.sendgrid_password, secure=True) verification_email = Mail(from_name="NYDKC Awards Committee", from_email="*****@*****.**", subject="Distinguished Key Clubber Application Verification for %s %s" % (applicant.first_name, applicant.last_name) ) verifier = "" if task == 'ltg': application.verification_ltg_email = self.request.get('ltg-email') application.verification_ltg_token = token application.verification_ltg_sent = True verification_email.add_to(application.verification_ltg_email) verifier = "Lieutenant Governor " + applicant.ltg.title() elif task == 'club-president': application.verification_club_president_email = self.request.get('club-president-email') application.verification_club_president_token = token application.verification_club_president_sent = True verification_email.add_to(application.verification_club_president_email) verifier = "Club President " + applicant.club_president.title() elif task == 'faculty-advisor': application.verification_faculty_advisor_email = self.request.get('faculty-advisor-email') application.verification_faculty_advisor_token = token application.verification_faculty_advisor_sent = True verification_email.add_to(application.verification_faculty_advisor_email) verifier = "Faculty Advisor " + applicant.faculty_advisor.title() template_values = { 'applicant': applicant, 'verification_url': verification_url, 'verifier': verifier } verification_email.set_html(JINJA_ENVIRONMENT.get_template('verification-email.html').render(template_values)) htmlhandler = html2text.HTML2Text() verification_email.set_text(htmlhandler.handle(verification_email.html).encode("UTF+8")) verification_email.add_unique_arg('user_id', user_id) code, response = sg.send(verification_email) response = json.loads(response) if response["message"] == "error": logging.error(("Problem with sending email to %s: " % verification_email.to) + str(response["errors"])) self._serve_page() return else: application.verification_applicant = True application.verification_applicant_date = datetime.now() application.put() self._serve_page()
def send_mail(): """ Send email with sendgrid sdk """ to_email = request.form.get('to') subject = request.form.get('subject') body = request.form.get('body') text_body = request.form.get('text_body') from_email = request.form.get('from') utf8_body = body.encode('utf-8') utf8_text_body = text_body.encode('utf-8') message = Mail() message.set_subject(subject) message.set_html(utf8_body) message.set_text(utf8_text_body) message.set_from(from_email) message.add_to(to_email) sg.send(message) logger.info("Email is sent to %s" % to_email) return ('', 204)