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 __init__(self, api_key, sender, recipient): self.api_key = api_key self.sender = sender self.recipient = recipient from sendgrid import SendGridClient self._sg = SendGridClient(self.api_key)
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 __init__(self, api_key, sender, recipient): """Initialize the service.""" self.api_key = api_key self.sender = sender self.recipient = recipient from sendgrid import SendGridClient self._sg = SendGridClient(self.api_key)
def __init__(self, sendgrid_account=None, sendgrid_password=None): self.sg = SendGridClient(sendgrid_account, sendgrid_password, raise_errors=True) self.sender = 'sendgrid' self.to_put = [] self.to_delete = []
def send_revocation_request_email(cfg, keyid, hex, user_email): # Send message using sendgrid api client = SendGridClient(cfg.config.sendgrid.api_key) message = get_sendgrid_request_message(cfg, keyid, hex, user_email) response = client.send(message) # Return JSON success message (response[1]) and HTTP status (response[0]) return response[1], response[0]
def send(sender_mail, send_to, subject, html, text=None): client = SendGridClient(current_app.config.get('SENDGRID_USERNAME'), current_app.config.get('SENDGRID_PASSWORD')) message = Mail() message.set_from(sender_mail) message.add_to(send_to) message.set_subject(subject) message.set_html(html) message.set_text(text) client.send(message)
def sendEmail(sender, recipient, subject, html, text): sg = SendGridClient('ecpf', 'Iheart1!', secure=True) message = Mail() message.set_subject(subject) message.set_html(html) message.set_text(text) message.set_from(sender) message.add_to(recipient) sg.send(message) return True
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 send_email(subject, body): """Send a message with stuff filled in for sleepybymail.""" client = SendGridClient(SENDGRID_USER, SENDGRID_PASS, raise_errors=True) message = Mail(from_email=FROM_EMAIL, to=TO_ADDR, subject=subject, html=body, text=body) status, msg = client.send(message) if status == 200: print "Message sent successfully." if status != 200: print "Message delivery failed." print "status", status print "msg", msg
def send_email(self, request): # make a secure connection to SendGrid sg = SendGridClient(get_mail_username(), get_mail_pass(), secure=True) # make a message object message = Mail() message.set_subject('message subject') message.set_html('<strong>HTML message body</strong>') message.set_text('plaintext message body') message.set_from('*****@*****.**') # add a recipient message.add_to('John Doe <*****@*****.**>') # use the Web API to send your message sg.send(message) return message_types.VoidMessage()
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 sendEmailWithSendGrid(sender, to, subject, body, html): # make a secure connection to SendGrid sg = SendGridClient(username, password, secure=True) # make a message object message = Mail() message.set_subject(subject) message.set_html(html) message.set_text(body) message.set_from(sender) # add a recipient message.add_to(to) logging.debug("message %s" % message) # use the Web API to send your message sg.send(message)
from pymongo import MongoClient from sendgrid import Mail, SendGridClient, SendGridClientError, SendGridServerError # Debug snippet: import pprint debug_printer = pprint.PrettyPrinter() assert (platform.python_version_tuple()[0:2] == ('3', '3')) if 'MONGOLAB_URI' in os.environ: # prod client = MongoClient(os.environ.get('MONGOLAB_URI')) else: # dev client = MongoClient(os.environ.get('MONGODB_URI')) sg = SendGridClient(os.environ.get('SENDGRID_ORANGE_KEY'), raise_errors=True) db = client.get_default_database() alert_text = "Tomorrow's weather earned a score of {}, which beats the threshold of {}. Visit https://saunter.io." def send_alerts(score, threshold): sub_list = db.subscribers.find_one({"_id": 13722}) for email in sub_list['emails']: message = Mail() message.add_to(email) message.set_subject("Nice weather alert") message.set_html(alert_text.format(score, threshold)) message.set_text(alert_text.format(score, threshold))
def setUp(self): self.sg = SendGridClient(SG_USER, SG_PWD)
def set_sendgrid_client(self, sendgrid_account, sendgrid_password): self.sg = SendGridClient(sendgrid_account, sendgrid_password, raise_errors=True)
def setUp(self): self.sg = SendGridClient(SG_USER, SG_PWD) self.maxDiff = None
def test_apikey_init(self): sg = SendGridClient(SG_PWD) self.assertEqual(sg.password, SG_PWD) self.assertIsNone(sg.username)
db.init_app(app) migrate = Migrate(app, db) manager = Manager(app) def make_shell_context(): return dict(app=app, db=db, User=User, Region=Region, Place=Place) manager.add_command('shell', Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) # Register blueprints app.register_blueprint(index.blueprint) app.register_blueprint(region.blueprint) login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'login' login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) hashids = Hashids(alphabet='abcdefghijklmnopqrstuvwxyz0123456789') sendgrid = SendGridClient(secrets.SENDGRID_USERNAME, secrets.SENDGRID_PASSWORD) if __name__ == '__main__': manager.run()
import stripe app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = environ.get('SECRET_KEY') app.config['STORMPATH_API_KEY_ID'] = environ.get('STORMPATH_API_KEY_ID') app.config['STORMPATH_API_KEY_SECRET'] = environ.get( 'STORMPATH_API_KEY_SECRET') app.config['STORMPATH_APPLICATION'] = environ.get('STORMPATH_APPLICATION') app.config['STRIPE_SECRET_KEY'] = environ.get('STRIPE_SECRET_KEY') app.config['STRIPE_PUBLISHABLE_KEY'] = environ.get('STRIPE_PUBLISHABLE_KEY') app.config['COINBASE_API_KEY'] = environ.get('COINBASE_API_KEY') sendgrid = SendGridClient( environ.get('SENDGRID_USERNAME'), environ.get('SENDGRID_PASSWORD'), ) stormpath_manager = StormpathManager(app) stormpath_manager.login_view = '.login' stripe.api_key = app.config['STRIPE_SECRET_KEY'] ##### Website @app.route('/') def index(): """Basic home page.""" return render_template('index.html')
""" Example of how to send a message. """ from sendgrid import SendGridClient, Mail import quickieconfig as qc SENDGRID_USER = qc.param("SENDGRID_USER") SENDGRID_PASS = qc.param("SENDGRID_PASS") FROM_EMAIL = qc.param("FROM_EMAIL") TO_ADDR = qc.param("TARGET_EMAIL") BODY = "foo" client = SendGridClient(SENDGRID_USER, SENDGRID_PASS, raise_errors=True) message = Mail(from_email=FROM_EMAIL, to=TO_ADDR, subject="test", text=BODY) status, msg = client.send(message) print "status", status print "msg", msg
def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery celery = make_celery(app) db = SQLAlchemy(app) lm = LoginManager(app) lm.login_view = 'index_page' sg = SendGridClient(app.config['SENDGRID_USER'], app.config['SENDGRID_API_KEY']) hashids = Hashids(salt=app.config.get('HASHIDS_SALT'), min_length=8) from app import views, tables, admins, apis # noqa: E402,F401 class LockedModelView(admins.AdminAccessModelView): can_delete = False class EditableModelView(admins.AdminAccessModelView): page_size = 50 admin = Admin(app,
def create_sendgrid(): return SendGridClient(Configuration.MAIL_USERNAME, Configuration.MAIL_PASSWORD, raise_errors=True)
def setup(): sg = SendGridClient(USER_NAME, PASSWORD) return sg
from flask import Flask, redirect, request, render_template, jsonify, make_response from sendgrid import Mail, SendGridClient import os app = Flask('PostCards') sg = SendGridClient(os.getenv('SG_USER'), os.getenv('SG_PWD')) # Post Schema # ID # from # image posts = {} @app.route('/', methods=['GET']) def new_postcard(): ID = len(posts) posts[ID] = {} return redirect('/edit/%s' % ID, code=302) @app.route('/edit/<int:ID>', methods=['GET', 'PUT']) def edit_handler(ID): if request.method == 'GET': return render_template('postcard.html', post=posts[ID], editor=True) else: posts[ID] = request.get_json() return jsonify(**posts[ID])
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', str(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()
from flask import (Flask, render_template, request, redirect, url_for, session, jsonify, flash) from flask.ext.bootstrap import Bootstrap from flask.ext.pymongo import PyMongo from sendgrid import SendGridClient, Mail, SendGridError app = Flask(__name__) app.config.from_object('config') mongo = PyMongo(app) sendgrid = SendGridClient(app.config['SENDGRID_USERNAME'], app.config['SENDGRID_PASSWORD'], raise_errors=True) Bootstrap(app) from forms import SendEmailForm DEFAULT_EMAIL_TEXT = """This is an e-mail sent from sample-email-sender Here is the sent info: first_name: %s last_name: %s country: %s city: %s Goodbye!""" @app.route('/', methods=['GET', 'POST'])