def test_header_functions(self): # add categories message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_category("category 1") self.assertEqual(message.header.as_json(), '{"category": ["category 1"]}', "Category added") message.add_category(["category 2", "category 3"]) self.assertEqual( message.header.as_json(), '{"category": ["category 1", "category 2", "category 3"]}', "Category list added") # add unique arguments message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.set_unique_arguments({ "customerAccountNumber": "55555", "activationAttempt": "1" }) self.assertEqual( message.header.as_json(), '{"unique_args": {"activationAttempt": "1", "customerAccountNumber": "55555"}}', "Unique arguments added") message.add_unique_argument("test", "some_value") self.assertEqual( message.header.as_json(), '{"unique_args": {"test": "some_value", "activationAttempt": "1", "customerAccountNumber": "55555"}}', "Unique argument added") # add header message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_header("x-test", "header1") self.assertEqual(message.headers, {"x-test": "header1"}, "Header added") # add filter settings message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_filter_setting("gravatar", "enable", 1) self.assertEqual( message.header.as_json(), '{"filters": {"gravatar": {"settings": {"enable": 1}}}}', "Filter setting added") # add sections message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.set_sections({"section1": "Section1", "section2": "Section2"}) self.assertEqual( message.header.as_json(), '{"section": {"section2": "Section2", "section1": "Section1"}}', "Sections added")
def test_recipients_adding(self): message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_to("*****@*****.**", "John Doe") self.assertEqual(message.to, ["*****@*****.**"], "Single email address added") self.assertEqual(message.to_name, ["John Doe"], "Single email address added") message.add_to(["*****@*****.**", "*****@*****.**"], ("John Doe", "Jane Doe")) self.assertEqual(message.to, [ "*****@*****.**", "*****@*****.**", "*****@*****.**", ], "Email list added") self.assertEqual(message.to_name, [ "John Doe", "John Doe", "Jane Doe", ], "Email list added") # following should replace existing to addresses and use x-smtpapi header instead message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") #invalid data data = { '*****@*****.**': { 'name': 'Name 1', 'code': 'Code 1' }, '*****@*****.**': { 'name': 'Name 2' }, } self.assertRaises(ValueError, message.add_to, data) #valid data data = { '*****@*****.**': { 'name': 'Name 1', 'code': 'Code 1' }, '*****@*****.**': { 'name': 'Name 2', 'code': 'Code 2' }, } message.add_to(data) self.assertEqual( message.header.as_json(), '{"to": ["*****@*****.**", "*****@*****.**"], "sub": {"code": ["Code 1", "Code 2"], "name": ["Name 1", "Name 2"]}}' ) self.assertEqual(message.to, ["*****@*****.**"]) self.assertEqual(len(message.to), 1)
def index(): option = {} option['filepicker_api_key'] = os.environ.get('FILEPICKER_API_KEY') if request.method == 'POST': option['file'] = request.form['file'] option['phone_number'] = request.form['phone_number'] try: body = "Check out this picture: %s?dl=false" % option['file'] if not re.match(r"[^@]+@[^@]+\.[^@]+", option['phone_number']): # Phone from_ = os.environ.get('TWILIO_FROM_NUMBER') client.sms.messages.create(to=option['phone_number'], from_=from_, body=body) else: # Email from_ = os.environ.get('SENDGRID_FROM_EMAIL') message = sendgrid.Message(from_, "Check out this picture", body, body) message.add_to(option['phone_number']) sg.web.send(message) option['message_sent'] = True except: option['message_sent'] = False return render_template('index.html', **option)
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 test_cc_bcc__attachment_adding(self): message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_cc("*****@*****.**") self.assertEqual(message.cc, ["*****@*****.**"], "CC address added") message.add_cc(["*****@*****.**", "*****@*****.**"]) self.assertEqual(message.cc, [ "*****@*****.**", "*****@*****.**", "*****@*****.**" ], "CC address added") message.add_bcc("*****@*****.**") self.assertEqual(message.bcc, ["*****@*****.**"], "BCC address added") message.add_bcc(["*****@*****.**", "*****@*****.**"]) self.assertEqual(message.bcc, [ "*****@*****.**", "*****@*****.**", "*****@*****.**" ], "BCC address added") message.add_attachment("file1.txt", "File data") self.assertEqual(message.attachments, [{ 'name': 'file1.txt', 'file': 'File data', 'cid': None }], "File attachment added")
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 test_web_transport_valid_password(self): fake_urlopen = fudge.Fake('urlopen') fake_response = fudge.Fake('fake_response') fake_urlencode = fudge.Fake('urlencode') urllib2 = fudge.patch_object("urllib2", "urlopen", fake_urlopen) fake_urlopen.expects_call().returns(fake_response) fake_response.expects("read").returns( '{"message": "success", "status": "ok"}') message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_to("*****@*****.**") urllib = fudge.patch_object("urllib", "urlencode", fake_urlencode) fake_urlencode.expects_call().with_args( { 'from': '*****@*****.**', 'api_user': '******', 'text': 'plain_text', 'to': ['*****@*****.**'], 'toname': [''], 'html': 'html', 'date': message.date, 'api_key': 'password', 'subject': 'subject1' }, 1).returns("") web_transport = web.Http('username', 'password') self.assertTrue(web_transport.send(message)) urllib.restore() urllib2.restore()
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 send_email(subject, send_to, template, content_type="plain", message=None, send_from=(settings.DEFAULT_FROM_EMAIL, "Moscow Trip Team")): if not message: message = {} message.update(add_default_context()) email_content = get_rendered_email_template(template, message) if content_type == 'html': message = sendgrid.Message(send_from, subject, html=email_content) else: message = sendgrid.Message(send_from, subject, text=strip_tags(email_content)) message.add_to(send_to) sendgrid_api.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_email_to_all_users(subject, text, html, from_address): for profile in Profile.objects.all(): try: message = sendgrid.Message(from_address, subject, text, html) message.add_to(profile.user.email, profile.name) send_message(message, profile.user, Email.DEFAULT) except: print 'something went wrong when sending an email to ' + profile.name
def create_welcome_message(from_address, to_address, to_name): html = '''<html><title>Welcome to Mutuality</title><body style = "margin:0px 0px 0px 0px;padding: 0px 0px 0px 0px; font-family: Tahoma, Geneva, sans-serif;"><!-- Start Main Table --><table width = "100%" height="100%" cellpadding = "0" style="padding:20px 0px 20px 0px" bgcolor="#FFFFFF"><table align="center"><tr><td width="460px" height="50px"><!-- Start Header --><table width="460px" cellpadding="0px" cellspacing="0" bgcolor="#6ba4c5" style = "color:#FFFFFF; font-weight: regular; padding: 16px 0px 16px 14px; font-family: Tahoma, Geneva, sans-serif;"><tr><td><a href='http://www.mymutuality.com?src=email_welcome'><img src="http://www.mymutuality.com/images/bigLogo.jpg" width="130" height="35" alt="Logo" border="0"></a></td></tr></table></td></tr></table><!-- End Header --><!-- Start Next Section --><table align="center"><tr><td width="460px" height="100px"><table cellpadding="0" cellspacing="0" width="460px" bgcolor="FFFFFF"><tr><td width="200" height="100" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 10px 10px 0px 15px; font-size: 16px; color:#000; font-weight:regular"><span style="font-size:34px; color:#989898; font-weight=regular">Welcome!</span><br><br>Creep.com? Never again.<br><br><br></td><td width="260" height="100" cellspacing="0" bgcolor="FFFFFF"><img src="http://www.mymutuality.com/images/carousel.jpg" alt="Image blocked" border="0"></td></tr></table></td></tr><tr><td><table cellpadding="0" cellspacing="0" width="460" bgcolor="FFFFFF"><tr><td width="200" height="120" bgcolor="FFFFFF" style="padding: 0px 0px 0px 20px"><img src="http://www.mymutuality.com/images/connected.jpg" alt="Image blocked" border="0"></td><td width="260" align="center" height="120" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 0px 0px 0px; font-size: 18px; color:#000; font-weight:regular">You are connected<br>to everyone you see.</td></tr></table></td></tr><tr><td><table cellpadding="0" cellspacing="0" width="460" bgcolor="FFFFFF"><tr><td width="260" align="center" height="120" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 0px 0px 0px; font-size: 18px; color:#000; font-weight:regular">Curious about someone?<br>Just ask a mutual friend.</td><td width="200" height="120" bgcolor="FFFFFF" style="padding: 0px 0px 0px 20px"><img src="http://www.mymutuality.com/images/ask.jpg" alt="Image blocked" border="0"></td></tr></table></td></tr><tr><td><table cellpadding="0" cellspacing="0" width="460" bgcolor="FFFFFF"><tr><td width="460px" align="left" height="20px" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 20px 0px 20px 0px; font-size:16px; color:#000; font-weight:regular">Mutuality (finally) makes meeting cool people safe and simple.<br><br>If you have any questions about Mutuality, please reply to us at <a href="mailto:[email protected]">[email protected]</a>.<br><br>Thanks,<br><br>The Mutuality Team</td></tr></table></td></tr></table><table width="460" cellpadding="0" cellspacing="0" align="center" bgcolor="#FFFFFF"><tr><td width="50"></td><td width="410" align="right" height="30" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 0px 0px 0px; font-size: 6px; color:#DDD; font-weight:regular; border-top:1px solid #DDD">This email was sent by Mutuality. Mutuality helps you meet cool people through your mutual friends.<br>If you received this in error, please click <a href="#" style="color:#ccc">here</a> to unsubscribe.</td></tr></table></table></body></html>''' text = "Greetings,\n\nWelcome to Mutuality!\n\nOn Mutuality, you are connected to everyone you see. If you want to learn more about somebody, you can quickly ask a mutual friend about them.\n\nMutuality (finally) makes meeting cool people safe and simple. If you have any questions or comments, please reply to us at [email protected].\n\nBest,\n\nThe Mutuality Team" subject = "Welcome to Mutuality" from_header = from_address message = sendgrid.Message(from_header, subject, text, html) message.add_to(to_address, to_name) message.add_category([Email.WELCOME]) return message
def CreatePostCard(self, url, toaddr, message, email): fd = urllib.urlopen(url) image_file = io.BytesIO(fd.read()) im = Image.open(image_file) width, height = im.size size = 600, 400 outfile = "temp.pdf" if height > width: im = im.rotate(90) width, height = im.size diagonal = (1.0 * width) / height if diagonal > 1.5: resizewidth = (600 * height) / 400 center = (width - resizewidth) / 2 im = im.crop((center, 0, width - center, height)) elif diagonal < 1.5: resizeheight = (400 * width) / 600 center = (height - resizeheight) / 2 im = im.crop((0, center, width, height - center)) im.thumbnail(size, Image.ANTIALIAS) if im.size != size: im = im.resize(size, Image.ANTIALIAS) im.save(outfile, "pdf", resolution=100.0) fromaddr = lob.Address.create(name="MHacks", address_line1="611 Woodward Ave", address_line2="", email="*****@*****.**", address_city="Detroit", address_state="MI", address_country="US", address_zip="48226").to_dict() PCName = str(datetime.now()) postcard = lob.Postcard.create(name=PCName, to=toaddr, message=message, front=open(outfile, 'rb'), from_address=fromaddr).to_dict() print postcard emailMessage = sendgrid.Message("*****@*****.**", "PinPost Recipt", message, "<p>" + message + "</p>") emailMessage.add_to(email, "PinPost User") emailMessage.add_attachment("PostCard.pdf", "outfile") try: s.web.send(emailMessage) except Exception, e: print "Could not send mail with sendgrid."
def notifyOfCommit(commit_msg, commit_url, repo_name, repo_url, owner_name, owner_email, committer): subject = "New commit on %s" % (repo_name, ) text_body = "There has been a new commit on the %s branch of %s by %s. The message was %s." % ( branch, repo_name, committer, commit_msg) html_body = "There has been a new commit on the %s branch of <a href=\"%s\" title=\"View on Github\">%s</a> by %s. The message was <a href=\"%s\" title=\"View commit on Github\">%s</a>" % ( branch, repo_url, repo_name, committer, commit_url, commit_msg) message = sendgrid.Message(from_param, subject, text_body, html_body) message.add_to(owner_email, owner_name) s.web.send(message)
def test_smtp_transport_wrong_password(self): fake_login = fudge.Fake('smtp.login') smtp_login = fudge.patch_object("smtplib.SMTP", "login", fake_login) fake_login.expects_call().with_args('username', 'password').raises( Exception("SMTP authentication error")) message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") smtp_transport = smtp.Smtp('username', 'password', tls=False) self.assertRaises(sendgrid.exceptions.SGServiceException, smtp_transport.send, message) smtp_login.restore()
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 create_new_message_message(from_address, to_address, to_name, sender_name, mutualFriendNumber, mutual_friend_name): from_header = from_address sender_first_name = sender_name.split()[0] subject = "New message from {0}".format(sender_name) text = "Greetings,\n\n{0} just sent you a message on Mutuality. You and {1} share {2} mutual friends including {3}.\n\nView the message at www.mymutuality.com/messages.\n\nBest,\n\nThe Mutuality Team".format( sender_name, sender_first_name, mutualFriendNumber, mutual_friend_name) html = '''<html><title>New message from {0}</title><body style = "margin:0px 0px 0px 0px; padding: 0px 0px 0px 0px; font-family: Tahoma, Geneva, sans-serif;"><!-- Start Main Table --><table width = "560px" height="170px" align="center" cellpadding="0" cellspacing="0" style="padding:10px 0px 10px 0px" bgcolor="#FFFFFF"><tr height="35px"><td align = "left" width="560px" cellpadding="0px" cellspacing="0" bgcolor="#6ba4c5" style = "color:#FFFFFF; font-weight: regular; padding: 1px 0px 0px 14px; font-family: Tahoma, Geneva, sans-serif;"><a href='http://www.mymutuality.com?src=email_new-message'><img src="http://www.mymutuality.com/images/LogoMedium.jpg" width="126" height="" alt="Logo" border="0"></a></td></tr><tr><td bgcolor="FFFFFF" height="30px" width="560px" align="left" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 10px 0px 15px; font-size: 16px; color:#000; font-weight:regular">{1} just sent you a message on Mutuality</td></tr><tr><td align="left" height="20px" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 0px 0px 15px; font-size: 12px; color:#000; font-weight:regular">You and {2} share <span style="font-size:18px; font-weight:bold">{3}</span> mutual friends including <span style="font-weight:bold">{4}.</td></tr><tr><td align="left" height="30" bgcolor="FFFFFF" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 15px 0px 15px; font-size: 16px; color:#000; font-weight:regular"><a href="http://www.mymutuality.com/messages?email_new-message">View the message on Mutuality</a></td></tr></table><table width="560" cellpadding="0" cellspacing="0" align="center" bgcolor="#FFFFFF"><tr><td width="50"></td><td width="410" align="right" height="30" style="font-family: Tahoma, Geneva, sans-serif; padding: 0px 0px 0px 0px; font-size: 6px; color:#DDD; font-weight:regular; border-top:1px solid #DDD">This email was sent by Mutuality. Mutuality helps you meet cool people through your mutual friends.<br>If you received this in error, please click <a href="#" style="color:#ccc">here</a> to unsubscribe.</td></tr></table></body></html>'''.format( sender_name, sender_name, sender_first_name, mutualFriendNumber, mutual_friend_name) message = sendgrid.Message(from_header, subject, text, html) message.add_to(to_address, to_name) message.add_category([Email.NEW_MESSAGE]) return 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 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 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 test_smtp_transport_valid_password(self): smtp_login = fudge.patch_object("smtplib.SMTP", "login", fudge.Fake('smtp.login')\ .expects_call().with_args('username', 'password')) smtp_sendmail = fudge.patch_object("smtplib.SMTP", "sendmail", fudge.Fake('smtp.sendmail')\ .expects_call()) smtp_quit = fudge.patch_object("smtplib.SMTP", "quit", fudge.Fake('smtp.quit')\ .expects_call()) message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_to("*****@*****.**", "John Doe") smtp_transport = smtp.Smtp('username', 'password', tls=False) self.assertTrue(smtp_transport.send(message)) smtp_login.restore() smtp_sendmail.restore() smtp_quit.restore()
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 test_web_transport_wrong_password(self): fake_urlopen = fudge.Fake('urlopen') fake_response = fudge.Fake('fake_response') urllib = fudge.patch_object("urllib2", "urlopen", fake_urlopen) fake_urlopen.expects_call().returns(fake_response) fake_response.expects("read").raises( FakeException( '{"message": "error", "errors": "Bad username / password"}')) message = sendgrid.Message("*****@*****.**", "subject1", "plain_text", "html") message.add_to("*****@*****.**") web_transport = web.Http('username', 'password') self.assertRaises(sendgrid.exceptions.SGServiceException, web_transport.send, message) urllib.restore()
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')