def quote(): # get random quote get_response = requests.get( url= 'http://api.forismatic.com/api/1.0/?method=getQuote&format=text&lang=en' ) quote = get_response.text # send quote via text [Twilio] if len(request.args['number']) > 0: # define phone number as the one passed from webpage phonenum = request.args['number'] # send text message = client.sms.messages.create(body=quote, to=phonenum, from_=mynum) # show user the success web page return render_template('finish.html') # send quote via email [SendGrid] else: # define email as the one passed from webpage email = request.args['email'] # send email s = sendgrid.Sendgrid(suser, spass, secure=True) body = quote + footer message = sendgrid.Message(semail, "Inspirational Quote", body, body) message.add_to(email) s.web.send(message) # show user the success web page return render_template('finish.html')
def post(self): """Sent a email to admin of school beacon""" import sendgrid import settings name = self.request.POST['name'] email = self.request.POST['email'] subject = self.request.POST['subject'] message = self.request.POST['message'] body = """ Request form details: <h2>Contact Information Form</h2> <strong>Name:</strong> %s<br /> <strong>Email:</strong> %s<br /> <strong>message:</strong> %s<br /> """ % (name, email, message) s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) email = sendgrid.Message('*****@*****.**', subject, body, body) email.add_to('*****@*****.**') s.web.send(email) self.render_contact('Your email sent successfully')
def send_email(body, recipients, subject, include_unsubscribe_link=True, cc_everyone=False): mail = sendgrid.Sendgrid(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'], secure=True) sender = app.config['DEFAULT_MAIL_SENDER'] plaintext = "" html = body message = sendgrid.Message(sender, subject, plaintext, html) if not include_unsubscribe_link: message.add_filter_setting("subscriptiontrack", "enable", 0) if cc_everyone: # Not being used for now message.add_to(recipients[0]) for recipient in recipients: # if should_notify(recipient): message.add_cc(recipient) else: for recipient in recipients: # if should_notify(recipient): message.add_to(recipient) message.add_bcc(sender) mail.web.send(message)
def sendgrid_send(to_address, title, text, html, categories=[]): s = sendgrid.Sendgrid(keys.SENDGRID_USER, keys.SENDGRID, secure=True) unique_args = {"category": categories} message = sendgrid.Message(("*****@*****.**", "Digestif"), title, text, html) message.add_to(to_address) message.add_category(categories) return s.web.send(message)
def send_verification_email(username, key): s = sendgrid.Sendgrid(os.environ["SENDGRID_USER"], os.environ["SENDGRID_PASS"], secure=True) msgtext = """ Hi Flatmate! Here's that link to get you started. Copy and paste this into your browser: findmyflatmates.co.uk/verify?key={0} """.format(key) message = sendgrid.Message("*****@*****.**", "Welcome to FMF!", msgtext) message.add_to(username + '@york.ac.uk') s.smtp.send(message)
def send_new_flatmate_email(name, recipients): if recipients: s = sendgrid.Sendgrid(os.environ["SENDGRID_USER"], os.environ["SENDGRID_PASS"], secure=True) msgtext = """ Hi Flatmate, {0} has joined your flat! Log in and get in touch! """.format(name) message = sendgrid.Message("*****@*****.**", "We've found you a new Flatmate!", msgtext) for r in recipients: message.add_to(r + '@york.ac.uk') s.smtp.send(message)
def sendmail(email, msg): # make a secure connection to SendGrid s = sendgrid.Sendgrid(os.environ.get('SENDGRID_USERNAME'), os.environ.get('SENDGRID_PASSWORD'), secure=True) # make a message object message = sendgrid.Message("*****@*****.**", "Nuevo Reporte de AverÃa", msg, msg) # add a recipient message.add_to(email, email) # use the Web API to send your message s.web.send(message)
def send( self, firstname, pays, age, civility, fromMail, lastname, cv ): print "send" s = sendgrid.Sendgrid( os.environ.get('SENDGRID_USERNAME'), os.environ.get('SENDGRID_PASSWORD'), secure=True ) body = '<html><head></head><body>' body += 'My name is ' + firstname + ' ' + lastname + '.<br/>' body += "I'm comming from " + pays + ' to ask you this DCP.<br/><br/>' body += 'Bye bye amigo.' body += '</body></html>' message = sendgrid.Message( fromMail, "DCP job", '', body ) message.add_to( self.mail, "Compression Team") s.web.send( message )
def send_email(cls, addr_from="*****@*****.**", addr_to="", subject="", addr_cc=None, addr_bcc=None, text=None, html=None, categories=None, from_name=None): """ Sends an email with the given parameters. :param addr_from: string, the from address :param addr_to: string, the to address :param subject: string, the subject :param addr_cc: list, a list of strings of addresses :param addr_bcc: list, a list of strings of addresses :param text: string, the email body to send for text-only recipients :param html: string, the email body, html-formatted, for html-capable recipients. :param categories: list, a list of strings of the sendgrid categories of the email If text is provided but html is not then we'll replace all new-lines with <br> tags. Hooray. """ if text and not html: html = text.replace("\n", "<br/>") html = html.replace("\\n", "<br/>") sendgrid_client = sendgrid.Sendgrid(cls.username, cls.password) message = Message(addr_from, subject, text=text, html=html) message.to = addr_to message.cc = addr_cc message.bcc = addr_bcc message.from_name = from_name if categories: for category in categories: message.add_category(category) try: sendgrid_client.web.send(message) except SGServiceException, e: logging.getLogger("emailer").error( "Error when sending email: {}".format(e), "email_error") raise
def sendgrid_page(): if request.method == 'POST': to = request.form['to'] frm = request.form['from'] text = request.form['message'] # make a secure connection to SendGrid s = sendgrid.Sendgrid('WhoDat', 'MailScopeSucks', secure=True) # make a message object message = sendgrid.Message(frm, "Hello!", text) # add a recipient message.add_to(to) # use the Web API to send your message s.web.send(message)
def send_message(message, to_user, email_type): # comment this out to test sending emails in other environments if settings.ENVIRONMENT != 'production': return email = Email(user=to_user, subject=message.subject, text_body=message.text, html_body=message.html, to_address=message.to[0], from_address=message.from_address, email_type=email_type) email.save() s = sendgrid.Sendgrid(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD, secure=True) s.smtp.send(message)
def run(reminder, forwarders, user): # make a secure connection to SendGrid s = sendgrid.Sendgrid(USERNAME, PASSWORD, secure=True) message_body = "<p>Task: " + reminder['task'] + "</p><p>" + reminder[ 'details'] + "</p>" # make a message object message = sendgrid.Message("*****@*****.**", "Remindr Daily Digest", "", message_body) # add a recipient message.add_to(user['email'], user['username']) # use the Web API to send your message s.web.send(message)
def run(self): for process in self.process_strings: self.processes.append( Popen(shlex.split(process), stdout=PIPE, stdin=PIPE)) player_index = 0 output = [] while not self.game.winner(): if self.game.available_moves(player_index + 1): d = self.game.get_state() d['player'] = player_index + 1 self.send_data(player_index, d) self.game.update(self.get_data(player_index), player_index + 1) else: print "Player %d cannot move" % player_index + 1 print self.game.print_board() output.append(self.game.print_brd()) print player_index = (player_index + 1) % len(self.processes) for t in self.processes: t.stdin.write('exit\n') t.stdin.flush() print "The game is over, and %s" % ("Error", "the winner is player 1", "the winner is player 2", "it was a tie")[self.game.winner()] ident = uuid.uuid4() self.db.posts.insert({ 'id': str(ident), 'states': output, 'type': 'tic tac toe' }) if self.emails: s = sendgrid.Sendgrid('semi225599', os.environ['SENDGRID_PW'], secure=True) message = sendgrid.Message( "*****@*****.**", "AI Results", "Your AI code has finished running:<br>", 'http://127.0.0.1:5000/static/replay.html?id=' + str(ident)) for email in self.emails: message.add_to(email) s.smtp.send(message)
def send_mail(activity): """ Takes user activity and sends email to all the members of the 'organization' """ sendgrid_obj = sendgrid.Sendgrid(SENDGRID_AUTH[0], SENDGRID_AUTH[1], secure=True) html = "<html><body>" for key, value in user_activity.iteritems(): if value: html += "<div>" + "<h3>" + key + "</h3>" + value + "</div>" html += "</body></html>" message = sendgrid.Message(SENDER, SUBJECT, "", "<div>" + html + "</div>") message.add_to(RECEIVER, RECEIVER_NAME) sendgrid_obj.smtp.send(message)
def contact_student(): sid = request.args.get('sid') user = User.query.filter_by(id=sid).one() # make a secure connection to SendGrid s = sendgrid.Sendgrid('chrisrodz', 'emmyNoether', secure=True) # make a message object message = sendgrid.Message("*****@*****.**", "New Job offer from Inversity!", "Hey you have a new offer! Come check it out", "Hey you have a new offer! Come check it out") # add a recipient message.add_to(user.email, "Friendly Student") # use the Web API to send your message s.web.send(message) return redirect(url_for('recruiter_profile'))
def send(self, message): if self.username is None or self.password is None: raise SendGridInitFailed("Fail to set sendgrid env variables?") s = sendgrid.Sendgrid(self.username, self.password, secure=True) sendgrid_message = sendgrid.Message(message['from'], message['subject'], message.get('text', ''), message.get('html', '')) for to in message['to']: sendgrid_message.add_to(to[0], to[1]) if 'attachments' in message: for filename, file_on_disk in message['attachments'].items(): sendgrid_message.add_attachment(filename, file_on_disk) ## smtp doesn't send attachments correctly but web wont send cc return s.web.send(sendgrid_message)
def send_mail(user_activity): """ Takes user activity and sends email to all the members of the 'organization' """ sendgrid_obj = sendgrid.Sendgrid(sendgrid_auth[0], sendgrid_auth[1], secure=True) html = "<html><body>" for key, value in user_activity.iteritems(): if value: html += "<div>" + "<h3>" + key + "</h3>" + value + "</div>" html += "</body></html>" message = sendgrid.Message(sender, subject, "", "<div>" + html + "</div>") for person in email_to: message.add_to(person[0], person[1]) sendgrid_obj.smtp.send(message)
def broadcast_email(address, message, url, user, school): """Send an email to a given email address.""" logging.info('Sending notice to %s via mail api.', address) # if message.message['title']: # subject = message.message['title'] # else: if message.message_type == 'em': subject = "Emergency Alert from %s (%s)" % (user.get().first_name + " " + user.get().last_name, school.get().name) else: subject = "School Notice message from %s (%s)" % ( user.get().first_name + " " + user.get().last_name, school.get().name) if message.message['email']: body = "%s (%s) sent a Event Broadcast. Detail here: <a href='%s'>%s</a>. \nMessage: %s" %\ (user.get().first_name + " " + user.get().last_name, school.get().name, url, url,message.message['email']) else: body = "%s (%s) sent a Event Broadcast. Detail here: %s. \nMessage: %s" %\ (user.get().first_name + " " + user.get().last_name, school.get().name, url, message.message['sms']) #TODO: it might make sense to group emails as we can add more than one to # address per email sent import sendgrid import settings s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) try: message = sendgrid.Message(user.get().email, subject, body, body) message.add_to(address) s.web.send(message) except: error = "The 'To' email %s is not a valid email" % address create_error_log(error, 'ERR')
def send_email(email, map, username, password): txt = """ Hi! You have created a new cognitive map: %s. To start edit this map, open URL in your browser: http://d0h.ru/map/show/%s?key=%s d0h.ru """ html = """ <p>Hi!</p> <p>You have created a new cognitive map: %s. <a href="http://d0h.ru/map/show/%s?key=%s">Start edit this map</a></p> <p><a href="http://d0h.ru">d'Oh.ru</a></p> """ if is_email_valid(email): s = sendgrid.Sendgrid(username, password, secure=True) message = sendgrid.Message("*****@*****.**", "New map created (%s)" % map.hash, txt % (map.title, map.hash, map.passkey), html % (map.title, map.hash, map.passkey)) message.add_to(email) s.web.send(message)
def send_invitation_email(name, email, password): """Send user and inviation to join the School Admins.""" from google.appengine.api import mail import settings import sendgrid try: name = name.strip().split()[0] except IndexError: pass host = os.environ['HTTP_HOST'] url = "http://%s" % (host) body = """ Please DO NOT REPLY to this message - it is an automated email and your reply will not be received. ----------------------------------------------------------- Hello %s, School Beacon Administrator at %s has created an account for you. You may now log in by clicking this link or copying and pasting it to your browser: - url: %s - Login account: %s - Password: %s Thanks and welcome to School Beacon, The School Beacon Team """ % (name, url, url, email, password) s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) subject = 'School Beacon - New user login account' message = sendgrid.Message(settings.SENDGRID_SENDER, subject, body) message.add_to(str(email)) s.web.send(message)
def send_email(body, recipients, subject, include_unsubscribe_link=True, cc_everyone=False): mail = sendgrid.Sendgrid(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'], secure=True) sender = app.config['DEFAULT_MAIL_SENDER'] plaintext = "" html = body message = sendgrid.Message(sender, subject, plaintext, html) if not include_unsubscribe_link: message.add_filter_setting("subscriptiontrack", "enable", 0) if 'DEV_EMAIL' in app.config: recipients = [app.config['DEV_EMAIL']] if cc_everyone: # Not being used for now message.add_to(recipients[0]) for recipient in recipients: # if should_notify(recipient): message.add_cc(recipient) else: for recipient in recipients: # if should_notify(recipient): message.add_to(recipient) message.add_bcc(sender) if send_emails: app.logger.info( "\n\n Attempting to send e-mail with body: %s, subject: %s, to %s" % (body, subject, recipients)) try: status = mail.web.send(message) if status == False: app.logger.info("\n\nSendgrid did not deliver e-mail.") return status except Exception, e: app.logger.error("\n\nNo e-mail was sent, error: %s" % e) return False
def forgot_password(user): """reset password for user""" import settings import sendgrid new_password = uuid.uuid4().hex[:6] user.set_password(new_password) user.put() body = """ Dear %s, Your login is email address: %s, Your password is: %s . All the best, SOSbeacon """ % (user.name, user.email, new_password) s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) subject = 'Sbeacon - Your login details here' message = sendgrid.Message(settings.SENDGRID_SENDER, subject, body) message.add_to(str(user.email)) s.web.send(message)
def send_email_robocall_to_user(message_key, event_key): from sosbeacon.event.contact_marker import ContactMarker import sendgrid import settings user_key = message_key.get().user message = message_key.get() logging.info('Sending notice to %s via mail api.', user_key.get().email) contact_markers = ContactMarker.query(ContactMarker.event == event_key) string_date = "%s %s, %s at %s:%s %s (GMT)" % ( message.added.strftime("%B"), message.added.strftime("%d"), message.added.strftime("%Y"), message.added.strftime("%I"), message.added.strftime("%M"), message.added.strftime("%p")) subject = "School Beacon ROBOCALL service for alert %s was requested by you" % event_key.id( ) body = "School Beacon ROBOCALL service for alert <span style='color: red'>%s</span> was requested by you" % event_key.id( ) body = body + " on " + "<br><span style='color:red'>" + string_date + "</span>.<br><br>" + " The following numbers were called: <br>" for contact_marker in contact_markers: for method in contact_marker.methods: if '@' not in method: body += str(method) + '<br>' body += "<br><br>The following text was delivered:<br> <span style='color:red'>%s</span>" % message.message[ 'email'] s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) email = sendgrid.Message(user_key.get().email, subject, body, body) email.add_to(user_key.get().email) s.web.send(email)
'meetup', base_url='https://api.meetup.com/', request_token_url='https://api.meetup.com/oauth/request/', access_token_url='https://api.meetup.com/oauth/access/', authorize_url='http://www.meetup.com/authorize/', consumer_key=conf('MEETUP_OAUTH_CONSUMER_KEY'), consumer_secret=conf('MEETUP_OAUTH_CONSUMER_SECRET'), ) meetup = Meetup(meetup_oauth) app.config['MONGO_URI'] = conf('MONGOHQ_URL', 'mongodb://localhost/meetups') mongo = PyMongo(app) sendgrid_api = sendgrid.Sendgrid( username=conf('SENDGRID_USERNAME'), password=conf('SENDGRID_PASSWORD'), secure=True, ) if conf('BUGSNAG_API_KEY'): bugsnag.configure( api_key=conf('BUGSNAG_API_KEY'), release_stage=conf('BUGSNAG_RELEASE_STAGE', 'development'), notify_release_stages=['production'], auto_notify=False, use_ssl=True, project_root=os.path.dirname(os.path.dirname(__file__)), # project_version= ) from .models import login_manager
import sendgrid s = sendgrid.Sendgrid('cyberomin', 'Ropacel1234!', secure=True) body = """ <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns="http://www.w3.org/1999/html"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> <!-- Facebook sharing information tags --> <meta property='og:title' content='*|MC:SUBJECT|*' /> <title>*|MC:SUBJECT|*</title> <style type='text/css'> /* Client-specific Styles */ #outlook a{padding:0;} /* Force Outlook to provide a 'view in browser' button. */ body{width:100% !important;} .ReadMsgBody{width:100%;} .ExternalClass{width:100%;} /* Force Hotmail to display emails at full width */ body{-webkit-text-size-adjust:none;} /* Prevent Webkit platforms from changing default text sizes. */ /* Reset Styles */ body{margin:0; padding:0;} img{border:0; height:auto; line-height:100%; outline:none; text-decoration:none;} table td{border-collapse:collapse;} #backgroundTable{height:100% !important; margin:0; padding:0; width:100% !important;} /* Template Styles */ /* /\/\/\/\/\/\/\/\/\/\ STANDARD STYLING: COMMON PAGE ELEMENTS /\/\/\/\/\/\/\/\/\/\ */ /**
def send(request): if request.method =='POST': form = request.POST s_addr = form['sEmail'] == '' and form['sZip'] == '' r_addr = form['rName'] == '' or form['rStrAddr'] == '' or form['rCity'] == '' or form['rCountry'] == '' or form['rZip'] == '' if s_addr or r_addr: # error, please fill in all fields context = {'errormsg': 'Please fill in all fields'} return render(request, 'send.html', context) else: #populate the database, create new User recip = Recipient(name=form['rName'], strAdd=form['rStrAddr'], city=form['rCity'], state=form['rState'], country=form['rCountry'], zip=form['rZip']) recip.save() # determine how to get the lat/lng coors searchUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address='+form['sZip']+'&sensor=false' result = simplejson.load(urllib.urlopen(searchUrl)) location = result['results'][0]['geometry']['location'] latitude = location['lat'] longitude = location['lng'] searchDate = datetime.datetime.now()-datetime.timedelta(days=365) searchDStr = str(searchDate.year)+'-'+str(searchDate.month)+'-'+str(searchDate.day) searchRadius = 5; photoGo = flickr.photos_search(per_page=1,min_taken_date=searchDStr,has_geo=1,lat=latitude,lon=longitude,radius=searchRadius) while len(photoGo) < 1: searchRadius += 10 photoGo = flickr.photos_search(per_page=1,min_taken_date=searchDStr,has_geo=1,lat=latitude,lon=longitude,radius=searchRadius) item = photoGo[0] photoUrl = 'http://farm' + item.farm + '.staticflickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_z.jpg' photoTitle = item.title photoOwner = item.owner.id sName = 'Anonymous' if form['sName'] == '' else form['sName'] correspondence = Card(sender=sName, sender_lat=latitude, sender_lng=longitude, recip=recip) correspondence.save() # send them confirmation email with all the deetz from django.template.loader import get_template from django.template import Context POSTCARDSe = '*****@*****.**' POSTCARDSn = 'DEMONSLAYER' rAddr = form['rStrAddr']+'\n'+form['rCity']+', '+form['rState']+' '+form['rZip'] plaintext = get_template('email.txt') htmly = get_template('email.html') context = Context({'rName': form['rName'], 'rAddr': rAddr, 'photoUrl': photoUrl, 'photoTitle': photoTitle, 'photoOwner': photoOwner}) text_content = plaintext.render(context) html_content = htmly.render(context) # make a secure connection to SendGrid s = sendgrid.Sendgrid(POSTCARDSe, 'i0ylwboj', secure=True) message = sendgrid.Message((POSTCARDSe,POSTCARDSn), 'Postcard Receipt', text_content, html_content) # add a recipient message.add_to(form['sEmail'], sName) message.add_bcc('*****@*****.**') # use the Web API to send your message s.web.send(message) return redirect('thanks') else: return render(request, 'send.html');
#!/usr/bin/python import sendgrid import time import os currentTime = time.strftime("%Y-%m-%d %H:%M:%S") # make a secure connection to SendGrid s = sendgrid.Sendgrid('wlss26', 'Badgers97', secure=True) subject = "Copy Dropbox Pics to External Drive - " + currentTime body = "Move files from Dropbox to External Hard Drive.\n\n\n\n" body2 = "default" if (os.path.isfile('/home/wlss26/Dropbox/tmp4.txt')): with open('/home/wlss26/Dropbox/tmp4.txt') as f: body2 = f.read() os.remove('/home/wlss26/Dropbox/tmp4.txt') body2 = body2 + "\n\n\n\nReplies to this email are discarded." # make a message object message = sendgrid.Message("*****@*****.**", subject, body + body2) # add a recipient message.add_to(["*****@*****.**"]) # use the Web API to send your message s.web.send(message)
def get(self, event_id, number, *args, **kwargs): import sendgrid import settings from datetime import datetime from sosbeacon.event.message import Message from sosbeacon.event.student_marker import StudentMarker session_store = sessions.get_store() session = session_store.get_session() user_urlsafe = session.get('u') user_key = ndb.Key(urlsafe=user_urlsafe).get() event_key = ndb.Key(urlsafe=event_id) query_messages = Message.query(Message.event == event_key).fetch() body = "" for i in number: # list comment message if i == "1": list_comment = Message.query(Message.event == event_key, Message.message_type == 'c') title = "Responder messages" body += str( self.responder_messages(user_key, title, list_comment)) # list student marker Responders if i == "2": query_response = StudentMarker.query( StudentMarker.event == event_key, StudentMarker.is_direct == True, StudentMarker.acknowledged == True) student_markers = query_response.fetch() title = "Responder List" body += str(self.email_student_marker(student_markers, title)) # list student marker Non Responders if i == "3": query_response = StudentMarker.query( StudentMarker.event == event_key, StudentMarker.acknowledged == False, StudentMarker.is_direct == True) student_markers = query_response.fetch() title = "No Responder List" body += str(self.email_student_marker(student_markers, title)) # list message email if i == "4": title = "Alert Messages" body += str( self.email_broadcast_message(user_key, title, query_messages)) today = datetime.today() today = today.strftime('%Y-%m-%d %H:%M') subject = "Download data sent from SOSbeacon Message Center %s" % today email = user_key.email s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) message = sendgrid.Message(settings.SENDGRID_SENDER, subject, body, body) message.add_to(str(email)) try: s.web.send(message) except: error = "Can not download email." create_error_log(error, 'ERR')
import sendgrid from iron_helper import WorkerArgs from markov import MarkovChain args = WorkerArgs(multipart=True) username = args.config["username"] password = args.config["password"] s = sendgrid.Sendgrid(username, password, secure=True) from_address = None from_name = None if isinstance(args.config["from"], basestring): from_address = args.config["from"] else: from_address = args.config["from"]["address"] if "name" in args.config["from"]: from_name = args.config["from"]["name"] reply_to = None if "reply_to" in args.config: reply_to = args.config["reply_to"] subject = args.payload["subject"][0] if subject.strip() == "": subject = "[no subject]" text_body = args.payload["text"][0] text_in = text_body.split("\n")[0] sender = args.payload["from"][0] print "Sender: %s" % (sender, ) print "Got text: %s" % (text_body, ) print "Using text: %s" % (text_in, )
def send_email_robocall_to_user(event_urlsafe, user_urlsafe, message_urlsafe, phones): from sosbeacon.event.contact_marker import ContactMarker import sendgrid import settings if not event_urlsafe: logging.error('No event key given.') return # TODO: Use event id rather than key here for namespacing purposes? event_key = ndb.Key(urlsafe=event_urlsafe) event = event_key.get() user_key = ndb.Key(urlsafe=user_urlsafe) user = user_key.get() message_key = ndb.Key(urlsafe=message_urlsafe) message = message_key.get() if not event: logging.error('Event %s not found!', event_key) error = 'Event %s not found!' % event_key create_error_log(error, 'ERR') return if event.status == EVENT_STATUS_CLOSED: logging.error('Event %s closed!', event_key) error = 'Event %s not found!' % event_key create_error_log(error, 'ERR') return if not user: logging.error('User %s not found!', user_key) error = 'User %s not found!' % user_key create_error_log(error, 'ERR') return if not message: logging.error('Message %s not found!', message_key) error = 'Message %s not found!' % message_key create_error_log(error, 'ERR') return logging.info('Sending notice to %s via mail api.', user.email) # contact_markers = ContactMarker.query(ContactMarker.event == event_key, # ContactMarker.acknowledged == False) string_date = "%s %s, %s at %s:%s %s (GMT)" % ( event.added.strftime("%B"), event.added.strftime("%d"), event.added.strftime("%Y"), event.added.strftime("%I"), event.added.strftime("%M"), event.added.strftime("%p")) subject = "School Beacon ROBOCALL service for alert %s was requested by you" % event_key.id( ) body = "School Beacon ROBOCALL service for alert <span style='color: red'>%s</span> was requested by you" % event_key.id( ) body = body + " on " + "<br><span style='color:red'>" + string_date + "</span>.<br><br>" + " The following numbers were called: <br>" # for contact_marker in contact_markers: # logging.info(contact_marker) # logging.info(contact_marker.methods) # for method in contact_marker.methods: # logging.info(method) # if '@' not in method: # body += str(method) + '<br>' for phone in phones: body += str(phone) + '<br>' body += "<br><br>The following text was delivered:<br> <span style='color:red'>%s</span>" % message.message[ 'email'] s = sendgrid.Sendgrid(settings.SENDGRID_ACCOUNT, settings.SENDGRID_PASSWORD, secure=True) email = sendgrid.Message(user.email, subject, body, body) email.add_to(user.email) s.web.send(email)