def post_sendgrid_api(module, username, password, from_address, to_addresses, subject, body, api_key=None, cc=None, bcc=None, attachments=None, html_body=False, from_name=None, headers=None): if not HAS_SENDGRID: SENDGRID_URI = "https://api.sendgrid.com/api/mail.send.json" AGENT = "Ansible" data = {'api_user': username, 'api_key':password, 'from':from_address, 'subject': subject, 'text': body} encoded_data = urllib.urlencode(data) to_addresses_api = '' for recipient in to_addresses: if isinstance(recipient, unicode): recipient = recipient.encode('utf-8') to_addresses_api += '&to[]=%s' % recipient encoded_data += to_addresses_api headers = { 'User-Agent': AGENT, 'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'} return fetch_url(module, SENDGRID_URI, data=encoded_data, headers=headers, method='POST') else: if api_key: sg = sendgrid.SendGridClient(api_key) else: sg = sendgrid.SendGridClient(username, password) message = sendgrid.Mail() message.set_subject(subject) for recip in to_addresses: message.add_to(recip) if cc: for recip in cc: message.add_cc(recip) if bcc: for recip in bcc: message.add_bcc(recip) if headers: message.set_headers(headers) if attachments: for f in attachments: name = os.path.basename(f) message.add_attachment(name, f) if from_name: message.set_from('%s <%s.' % (from_name, from_address)) else: message.set_from(from_address) if html_body: message.set_html(body) else: message.set_text(body) return sg.send(message)
def comment_mail_send(sender, instance, created, **kwargs): # print dir(instance) if instance.is_public == True: sg = sendgrid.SendGridClient( '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' ) message = sendgrid.Mail(to=instance.user_email, subject='Comment is published', html=instance.name + ', Your comment is published', text='Body', from_email='*****@*****.**') status, msg = sg.send(message) else: sg = sendgrid.SendGridClient( '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' ) message = sendgrid.Mail( to=instance.user_email, subject='Your comment is on moderation', html=instance.name + ', Your last comment is succesfully saved. Please, wait for moderation.', text='Body', from_email='*****@*****.**') status, msg = sg.send(message)
def send_feedback_ae_email(self, email_address, name, feedback_count, lesson_key, enrolled_on, has_narrative=False): #sendgrid generic stuff sent = False subject, body = self.get_feedback_ae_email_body( name, feedback_count, lesson_key, enrolled_on, has_narrative) if subject is not None and body is not None: #send the email! sg = sendgrid.SendGridClient(SENDGRID_API_KEY) message = sendgrid.Mail() message.set_subject(subject) message.set_html(body) #change the value for message.set_from to your from email address message.set_from('<YOUR_FROM_EMAIL_ADDRESS_HERE>') message.add_to(email_address) status, msg = sg.send(message) if status == 200: sent = True return sent
def forgot_password(request): if request.method == "POST": try: user = User.objects.get(email=request.POST.get("email")) chars = string.ascii_uppercase + string.digits + string.ascii_lowercase pwd_token = ''.join(random.choice(chars) for i in range(20)) user.set_password(pwd_token) user.save() message = "<p><b>Hello " + user.first_name + ",</b></p><p>We got a request to reset your password.</p>" message += "<p>Here is your new password: "******"</p>" sg = sendgrid.SendGridClient(SG_USER, SG_PWD) sending_msg = sendgrid.Mail() sending_msg.set_subject("Reset Your Password") sending_msg.set_html(message) sending_msg.set_text('Reset Your Password') sending_msg.set_from("*****@*****.**") sending_msg.add_to(request.POST.get('email')) sg.send(sending_msg) data = { 'error': False, "message": "Password has been sent to your email sucessfully." } except ObjectDoesNotExist: data = {'error': True, "message": "Entered Email id is incorrect."} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
def _send_with_sendgrid(from_addr, to_addr, subject, message, mimetype='html', categories=None, attachment_name=None, attachment_content=None, client=None): if (settings.SENDGRID_WHITELIST_MODE and to_addr in settings.SENDGRID_EMAIL_WHITELIST ) or settings.SENDGRID_WHITELIST_MODE is False: client = client or sendgrid.SendGridClient(settings.SENDGRID_API_KEY) mail = sendgrid.Mail() mail.set_from(from_addr) mail.add_to(to_addr) mail.set_subject(subject) if mimetype == 'html': mail.set_html(message) else: mail.set_text(message) if categories: mail.set_categories(categories) if attachment_name and attachment_content: mail.add_attachment_stream(attachment_name, attachment_content) status, msg = client.send(mail) return status < 400 else: sentry.log_message( 'SENDGRID_WHITELIST_MODE is True. Failed to send emails to non-whitelisted recipient {}.' .format(to_addr))
def send_email(htmlbody, subject, email_list): # using SendGrid's Python Library - https://github.com/sendgrid/sendgrid-python x = SGFields.objects.get(id=1) u = x.sgusername p = x.sgpassword sg = sendgrid.SendGridClient(u, p) message = sendgrid.Mail() """ message.add_filter('templates', 'enable', '1') message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID') message.add_substitution('key', 'value') message.add_to("*****@*****.**") message.set_from("*****@*****.**") message.set_subject("Sending with SendGrid is Fun") message.set_html("and easy to do anywhere, even with Python") message.add_to_name("Jesse Dovi") message.set_from_name("Dovi Motors Inc.") """ message.add_to(email_list) message.set_from_name("Dovi Motors Inc.") message.set_from("*****@*****.**") message.set_subject(subject) message.set_html(htmlbody) status, msg = sg.send(message) return (status,msg)
def send_welcome_email(url, distribuidor): sg = sendgrid.SendGridClient(settings.SENDGRID_API_KEY) url = url message = sendgrid.Mail() message.add_to(' <' + distribuidor.user.email + '>') message.set_html('Body') message.set_text('Body') message.set_subject('Verificar correo') message.set_from('CMC <*****@*****.**>') # You pass substitutions to your template like this message.add_substitution('-first_name-', distribuidor.user.first_name) message.add_substitution('-last_name-', distribuidor.user.last_name) message.add_substitution('-url-', url) # Turn on the template option message.add_filter('templates', 'enable', '1') # Tell SendGrid which template to use message.add_filter('templates', 'template_id', '6a5fe8fd-21bd-482c-ae23-eb1b75b2f0ca') # Get back a response and status status, msg = sg.send(message)
def do_mail(email, link) : msg_txt = """Congratulations! Your .gov.ify-ed file is now available for download, printing and sharing at the following URL: {0} Nice job! And while the file is real, this whole thing is really just an April Fool's joke from the merry pranksters at the OpenGov Foundation. Hope you enjoyed it. Now, come check out our authentic open data work and our serious open source projects on Github. http://opengovfoundation.org/ """.format(link) msg_html = """Congratulations! Your .gov.ify-ed file is now available for download, printing and sharing at the following URL:<br/> <br/> <a href="{0}">{0}</a><br/> <br/> Nice job! And while the file is real, this whole thing is really just an April Fool's joke from the merry pranksters at the <a href="http://opengovfoundation.org/">OpenGov Foundation</a>. Hope you enjoyed it. Now, come check out our authentic <a href="http://americadecoded.org/">open data work</a> and our serious <a href="https://github.com/opengovfoundation">open source projects</a> on Github. """.format(link) sg = sendgrid.SendGridClient(config.sendgrid['USERNAME'], config.sendgrid['PASSWORD']) message = sendgrid.Mail(to=email, subject='.gov.ify : Your Government-Ready PDF Is Ready for Download!', html=msg_html, text=msg_txt, from_email=config.sendgrid['FROM']) status, msg = sg.send(message)
def send(request): profile = UserProfile.objects.get(user_id=request.POST['to']) if profile.pref: user = API_KEYS['SG_USER'] pw = API_KEYS['SG_PASS'] reciever = profile.email subject = request.POST['subject'] body = request.POST['body'] sg = sendgrid.SendGridClient(user, pw) message = sendgrid.Mail() message.add_to(reciever) message.set_subject(subject) message.set_html(body) message.set_text(body) message.set_from(request.user.get_profile().email) print reciever print(sg.send(message)) else: account_sid = API_KEYS["TWILIO_SID"] auth_token = API_KEYS["TWILIO_AUTH"] txtfrom = API_KEYS["TWILIO_NUM"] body = request.POST['subject'] + ": " + request.POST['body'] txtto = profile.phone client = TwilioRestClient(account_sid, auth_token) message = client.sms.messages.create( body=body, to=txtto, # Replace with your phone number from_=txtfrom) # Replace with your Twilio number print message.sid return HttpResponseRedirect('/success')
def send_email_primary(self): """ Send email using primary service (Sendgrid) Returns True on success, False otherwise """ sg = sendgrid.SendGridClient(constants.SENDGRID_USERNAME, constants.SENDGRID_PASSWORD, raise_errors=True) message = sendgrid.Mail() message.add_to(self.to_addresses) if self.cc_addresses: message.add_cc(self.cc_addresses) if self.bcc_addresses: message.add_cc(self.bcc_addresses) message.set_subject(self.subject) message.set_text(self.body) message.set_from(self.from_address) try: status, msg = sg.send(message) except sendgrid.SendGridClientError: return False except sendgrid.SendGridServerError: return False return True
def send_email(num_csvs): """ """ sender = sendgrid.SendGridClient(SENDGRID_API_KEY) email = sendgrid.Mail() email.set_subject('CSV Generation') email.add_to('*****@*****.**') email.set_from('*****@*****.**') email.set_from_name('CSV Generation Tool') email.set_replyto('*****@*****.**') message = """ <h3>Another CSV update has been completed!</h3> <p>A total of {} files (x2) were added just now.</p> """.format(num_csvs) email.set_html(message) status, msg = sender.send(email) print(status, msg) return
def _send_to_sendgrid(self, message, email_addresses, cc=None, bcc=None, sender=None): username = (base.secret('sendgrid_low_priority_username') or base.secret('sendgrid_username')) password = (base.secret('sendgrid_low_priority_password') or base.secret('sendgrid_password')) assert username and password, "Can't find sendgrid username/password" client = sendgrid.SendGridClient(username, password, raise_errors=True) # The sendgrid API client auto-utf8-izes to/cc/bcc, but not # subject/text. Shrug. msg = sendgrid.Mail(subject=self._get_summary().encode('utf-8'), to=email_addresses, cc=cc, bcc=bcc) if self.html: # TODO(csilvers): convert the html to text for 'body'. # (see base.py about using html2text or similar). msg.set_text(message.encode('utf-8')) msg.set_html(message.encode('utf-8')) else: msg.set_text(message.encode('utf-8')) # Can't be keyword arg because those don't parse "Name <email>" # format. msg.set_from(_get_sender(sender)) client.send(msg)
def main(): r = requests.get('http://weerlive.nl/api/json-data-10min.php?key=demo&locatie=Amsterdam') j = r.json() sender = os.environ['FROM'] sendgrid_pass = os.environ['SENDGRID_PASSWORD'] sendgrid_user = os.environ['SENDGRID_USERNAME'] min_temp_morgen = int(j['liveweer'][0]['d1tmin']) min_temp_overmorgen = int(j['liveweer'][0]['d2tmin']) text = "Hallo, het gaat morgen of overmorgen vriezen. Zet je plantjes binnen! Gr. Mink" if (min_temp_morgen < 1 or min_temp_overmorgen < 30): # Het gaat vriezen import sendgrid sg =sendgrid.SendGridClient(sendgrid_user, sendgrid_pass) message = sendgrid.Mail(subject='Het gaat vriezen! Zet je planten binnen.', text=text, from_email = sender) else: return for to in ['*****@*****.**', '*****@*****.**']: message.add_to(to) status, msg = sg.send(message) print(msg) if status is not 200: sys.exit(1)
def new_post(request): if request.method == 'POST': validate_blog = BlogpostForm(request.POST) if validate_blog.is_valid(): blog_post = validate_blog.save(commit=False) blog_post.user = request.user blog_post.meta_description = request.POST['meta_description'] blog_post.status = 'D' if request.POST.get('status') == "P": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'P' elif request.POST.get('status') == "T": if request.user.user_roles == "Admin" or request.user.is_special or request.user.is_superuser: blog_post.status = 'T' blog_post.save() if request.POST.get('tags', ''): tags = request.POST.get('tags') tags = tags.split(',') for tag in tags: blog_tag = Tags.objects.filter(name=tag) if blog_tag: blog_tag = blog_tag[0] else: blog_tag = Tags.objects.create(name=tag) blog_post.tags.add(blog_tag) sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) sending_msg = sendgrid.Mail() sending_msg.set_subject("New blog post has been created") blog_url = 'https://www.micropyramid.com/blog/view-post/' + str( blog_post.slug) + '/' message = '<p>New blog post has been created by ' + str( request.user) + ' with the name ' + str( blog_post.title) + ' in the category ' message += str( blog_post.category.name ) + '.</p>' + '<p>Please <a href="' + blog_url + '">click here</a> to view the blog post in the site.</p>' sending_msg.set_html(message) sending_msg.set_text('New blog post has been created') sending_msg.set_from(request.user.email) sending_msg.add_to( [user.email for user in User.objects.filter(is_admin=True)]) sg.send(sending_msg) data = {'error': False, 'response': 'Blog Post created'} else: data = {'error': True, 'response': validate_blog.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') categories = Category.objects.all() c = {} c.update(csrf(request)) return render(request, 'admin/blog/blog-new.html', { 'categories': categories, 'csrf_token': c['csrf_token'] })
def send_confirmation(email_address, confirm_key): api_user = '******' api_key = open('/home/ubuntu/auth/sendgrid', 'r').read() email_to = email_address email_bcc = '*****@*****.**' email_from = '*****@*****.**' subject = '[ACTION REQUIRED] Confirm your new kar.yt address' body = 'Thank you for registering a Karyt address<p>' body += 'Click the following link to complete your registration:<p>' body += 'http://kar.yt/confirm/' + confirm_key sg = sendgrid.SendGridClient(api_user, api_key) message = sendgrid.Mail() message.add_to(email_to) message.add_bcc(email_bcc) message.set_from(email_from) message.set_subject(subject) message.set_html(body) sys.stderr.write( '\n> sending confirmation email to: {}\n'.format(email_to)) (http_status_code, message) = sg.send(message) sys.stderr.write('> response_code: {}\n'.format(http_status_code)) sys.stderr.write('> response_json: {}\n\n'.format(message))
def index(): if request.method == 'POST': email = request.form['email'] if not email: return render_template('index.html') user = Users.find_one({'email': email}) if not user: user_id = Users.create(email) sg = sendgrid.SendGridClient("justindonato750", app.config["SMTP_PASS"]) message = sendgrid.Mail() message.add_to(email) message.set_subject("Welcome to Exercredit") message.set_html(render_template('welcome-inlined.html', user_id=user_id)) message.set_from('*****@*****.**') status, msg = sg.send(message) print status, msg return redirect('/user/%s/exercises?add=1' % user_id) else: print "flashing message" flash('Sorry, this email has already been registered. You should already be getting a daily email.', 'error') return render_template('index.html')
def _send_with_sendgrid(from_addr, to_addr, subject, message, mimetype='html', categories=None, attachment_name=None, attachment_content=None, client=None): client = client or sendgrid.SendGridClient(settings.SENDGRID_API_KEY) mail = sendgrid.Mail() mail.set_from(from_addr) mail.add_to(to_addr) mail.set_subject(subject) if mimetype == 'html': mail.set_html(message) else: mail.set_text(message) if categories: mail.set_categories(categories) if attachment_name and attachment_content: mail.add_attachment_stream(attachment_name, attachment_content) status, msg = client.send(mail) return status < 400
def send_email(data, key, request=None, use_https=False): with open('djangoctf/settings.json') as config_file: config = json.loads(config_file.read()) sendgrid_api_key = config['email']['sendgrid_api_key'] use_https = config['ssl'] current_site = get_current_site(request) link_protocol = 'https' if use_https else 'http' with open('ctfapp/templates/activation_email_template.txt', 'r') as template_file: template = Template(template_file.read()) context = Context({ 'activation_key': key, 'username': data['username'], 'domain': current_site.domain, 'protocol': link_protocol }) message_text = template.render(context) # Send an activation email through sendgrid message_to_field = data['email'] sg = sendgrid.SendGridClient(sendgrid_api_key) message = sendgrid.Mail() message.smtpapi.add_to(message_to_field) message.set_subject('Activation Link for angstromCTF') message.set_text(message_text) message.set_from('angstromCTF team <*****@*****.**>') sg.send(message)
def send_contact_email(request): context = RequestContext(request) sg = sendgrid.SendGridClient(settings.SENDGRID_API_KEY) name = request.POST.get('name') last_name = request.POST.get('last_name') email = request.POST.get('email') message_content = request.POST.get('message') message = sendgrid.Mail() message.add_to('<*****@*****.**>') message.set_html('Body') message.set_text('Body') message.set_subject('Contacto desde la pagina web') message.set_from('<' + email + '>') # You pass substitutions to your template like this message.add_substitution('-name-', name) message.add_substitution('-last_name-', last_name) message.add_substitution('-email-', email) message.add_substitution('-message-', message_content) # Turn on the template option message.add_filter('templates', 'enable', '1') # Tell SendGrid which template to use message.add_filter('templates', 'template_id', 'b805c9e2-c601-4fc1-83c9-e5eeb5026153') # Get back a response and status status, msg = sg.send(message) return render_to_response('contact_form_confirm.html', {'pageType': 'Contact Form Confirm'}, context)
def __init__(self): logging.basicConfig() self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) self.garage_data = anyconfig.load("garage_data.json")['garage_data'] self.sg = sendgrid.SendGridClient(SENDGRID_USERNAME, SENDGRID_PASSWORD) self.keen_client = None
def register_user_mail(request, distribuidor): sg = sendgrid.SendGridClient(settings.SENDGRID_API_KEY) message = sendgrid.Mail() message.add_to(' <*****@*****.**>') message.set_html('Body') message.set_text('Body') message.set_subject('Un nuevo usiario quiere ser distribuidor') message.set_from(' <' + distribuidor.user.email + '>') # You pass substitutions to your template like this message.add_substitution('-first_name-', distribuidor.user.first_name) message.add_substitution('-last_name-', distribuidor.user.last_name) message.add_substitution('-telephone-', distribuidor.user.telephone) message.add_substitution('-email-', distribuidor.user.email) # Turn on the template option message.add_filter('templates', 'enable', '1') # Tell SendGrid which template to use message.add_filter('templates', 'template_id', '5e91fb1a-c2fd-4c45-99a6-49fe0dcaee71') # Get back a response and status status, msg = sg.send(message)
class Sender(): dbconfig = {} user = '' userPwd = '' address = '' db = '' connect_str = 'mysql+mysqlconnector://'+user+':'+userPwd+'@'+address+'/'+db config = []#nombre, correo, teléfono #https://docs.python.org/3/library/csv.html with open('cfg.csv') as csvfile: #personas = csv.reader(csvfile, delimiter=' ', quotechar='|') personas = csv.DictReader(csvfile) for persona in personas: config.append(persona) #sendgrid API client = sendgrid.SendGridClient(config['mail']['key']) message = sendgrid.Mail() message.set_from(config['mail']['from_transaction']) message.set_from_name(config['mail']['from_transaction_name']) message.add_category('Reminder') message.add_filter('templates', 'enable', '1') message.add_filter('templates', 'template_id', 'db8bcf66-5c0c-4f54-ab40-60f1f92fd9a1') message.add_to('') message.add_to('*****@*****.**') message.add_to('-email-') message.set_replyto('hola@activistadigital')#reply_to email goes here message.set_subject('Hola -name-, este es un recordatorio de Clinicamia') message.set_html('<h2>Hola -name-,</h2></br>Este es un recordatorio para que .') def set_data(self, data): self.message.add_substitution('-name-', data['name']) print(data['name'])
def change_status_email(sender, teamname, recipient): try: API_USER = '******' API_KEY = 'roar@dude1' signer = Signer() encrypteduserid = signer.sign(sender.id) print recipient.email print teamname print sender.first_name print sender.last_name mail_to = recipient.email subject = 'Change Of {0} Status !'.format(teamname) mail_from = '*****@*****.**' sg = sendgrid.SendGridClient(API_USER, API_KEY) message = sendgrid.Mail() message.add_filter('templates', 'enable', '1') message.add_filter('templates', 'template_id', 'b428616f-f29f-4896-8de5-725c6126b0a4') message.add_to(mail_to) message.add_substitution('[%first_name%]', sender.first_name) message.add_substitution('[%last_name%]', sender.last_name) message.set_subject(subject) message.set_from(mail_from) status, msg = sg.send(message) print "HTTP STATUS", status msg = json.loads(msg) except Exception as e: raise e
def sendemail(recipient, message): """take a recipient email address and message, email the message. return a tuple of http status code and ? message""" sg = sendgrid.SendGridClient(Sendgrid_API_key) message.add_to(recipient) status, msg = sg.send(message) return (status, msg)
def Memail(mto, mfrom, msubject, mbody, email_template_name, context): if settings.MAIL_SENDER == 'AMAZON': send_mail(msubject, email_template_name, context, mfrom, mto) elif settings.MAIL_SENDER == 'MAILGUN': requests.post(settings.MGUN_API_URL, auth=('api', settings.MGUN_API_KEY), data={ 'from': mfrom, 'to': mto, 'subject': msubject, 'html': mbody }) elif settings.MAIL_SENDER == 'SENDGRID': sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) sending_msg = sendgrid.Mail() sending_msg.set_subject(msubject) sending_msg.set_html(mbody) sending_msg.set_text(msubject) sending_msg.set_from(mfrom) sending_msg.add_to(mto) reposne = sg.send(sending_msg) print(reposne) else: text_content = msubject msg = EmailMultiAlternatives(msubject, mbody, mfrom, mto) msg.attach_alternative(mbody, "text/html") msg.send()
def sendgrid_send(m): sg = sendgrid.SendGridClient(settings.SENDGRID_API_KEY) # create message message = sendgrid.Mail() message.set_subject(m.get('subject', '')) message.set_from(m.get('from_email', '')) message.set_from_name(m.get('from_name', '')) if 'replyto' in m: message.set_replyto(m['replyto']) if 'text' in m: message.set_text(m['text']) if 'html' in m: message.set_html(inline_css(m['html'])) for recipient in m.get('to', []): message.add_to(recipient['email']) for tag in m.get('tags', []): message.add_category(tag) sg.send(message)
def Memail(mto, mfrom, msubject, mbody, user_active): mfrom = settings.DEFAULT_FROM_EMAIL if user_active: mail_sender = settings.MAIL_SENDER else: mail_sender = settings.INACTIVE_MAIL_SENDER if mail_sender == 'AMAZON': # conn=SESConnection(settings.AM_ACCESS_KEY, settings.AM_PASS_KEY) conn = boto.ses.connect_to_region( 'eu-west-1', aws_access_key_id=settings.AM_ACCESS_KEY, aws_secret_access_key=settings.AM_PASS_KEY ) conn.send_email(mfrom, msubject, mbody, mto, format='html') elif mail_sender == 'MAILGUN': requests.post( settings.MGUN_API_URL, auth=('api', settings.MGUN_API_KEY), data={ 'from': mfrom, 'to': mto, 'subject': msubject, 'html': mbody, }) elif mail_sender == 'SENDGRID': sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) sending_msg = sendgrid.Mail() sending_msg.set_subject(msubject) sending_msg.set_html(mbody) sending_msg.set_text(msubject) sending_msg.set_from(mfrom) sending_msg.add_to(mto) sg.send(sending_msg) else: pass
def __init__(self, _from, _to, _subject, _content): self.client = sendgrid.SendGridClient('maliksjsu', 'Anaconda@2') self.message = sendgrid.Mail() self.set_from = _from self.to = _to self.subject = _subject self.content = _content
def post(self): name = self.get_argument("name", "").encode("utf-8") email = self.get_argument("email", "").encode("utf-8") subject = self.get_argument("subject", "").encode("utf-8") message = self.get_argument("message", "").encode("utf-8") if name == "" or email == "" or subject == "" or message == "": self.write("Debe ingresar los campos requeridos") else: sg = sendgrid.SendGridClient(sendgrid_user, sendgrid_pass) mensaje = sendgrid.Mail() mensaje.set_from("{nombre} <{mail}>".format(nombre=name, mail=email)) mensaje.add_to(to_giani) mensaje.set_subject("Contact GDF - {}".format(subject)) mensaje.set_html(message) status, msg = sg.send(mensaje) if status == 200: self.render( "message.html", message="Gracias por contactarte con nosotros, su mensaje \ ha sido enviado exitosamente") else: self.render( "beauty_error.html", message="Ha ocurrido un error al enviar su mensaje, {}". format(msg))
def _send_with_sendgrid(from_addr, to_addr, subject, message, categories=None, attachment_name=None, attachment_content=None, client=None): if (settings.SENDGRID_WHITELIST_MODE and to_addr in settings.SENDGRID_EMAIL_WHITELIST) or settings.SENDGRID_WHITELIST_MODE is False: client = client or sendgrid.SendGridClient(settings.SENDGRID_API_KEY) mail = sendgrid.Mail() mail.set_from(from_addr) mail.add_to(to_addr) mail.set_subject(subject) mail.set_html(message) if categories: mail.set_categories(categories) if attachment_name and attachment_content: mail.add_attachment_stream(attachment_name, attachment_content) status, msg = client.send(mail) if status >= 400: sentry.log_message( '{} error response from sendgrid.'.format(status) + 'from_addr: {}\n'.format(from_addr) + 'to_addr: {}\n'.format(to_addr) + 'subject: {}\n'.format(subject) + 'mimetype: html\n' + 'message: {}\n'.format(message[:30]) + 'categories: {}\n'.format(categories) + 'attachment_name: {}\n'.format(attachment_name) ) return status < 400 else: sentry.log_message( 'SENDGRID_WHITELIST_MODE is True. Failed to send emails to non-whitelisted recipient {}.'.format(to_addr) )