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 contact(request): if request.method == 'GET': return render(request, 'site/pages/contact-us.html') validate_contact = ContactForm(request.POST) if validate_contact.is_valid(): if 'enquery_type' in request.POST.keys(): Contact.objects.create( country=request.POST.get('country'), enquery_type=request.POST.get('enquery_type')) message = "<p>From: " + request.POST.get( 'full_name') + "</p><p>Email Id: " message += request.POST.get('email') + \ "</p><p>Message: "+request.POST.get('message')+"</p>" if request.POST.get('phone'): message += "<p>Contact Number: " + request.POST.get( 'phone') + "</p>" if request.POST.get('enquery_type'): message += "<p><b>General Information: </b></p>"+"<p>Enquery Type: " +\ request.POST.get('enquery_type')+"</p>" if request.POST.get('country'): message += "<p>Country: " + request.POST.get('country') + "</p>" sg = sendgrid.SendGridClient(settings.SG_USER, settings.SG_PWD) contact_msg = sendgrid.Mail() contact_msg.set_subject("We received your message | MicroPyramid") message_reply = 'Hello ' + request.POST.get('full_name') + ',\n\n' message_reply = message_reply + 'Thank you for writing in.\n' message_reply = message_reply + \ 'We appreciate that you have taken the time to share your feedback with us! We will get back to you soon.\n\n' message_reply = message_reply + 'Regards\n' message_reply = message_reply + 'The MicroPyramid Team.' contact_msg.set_text(message_reply) contact_msg.set_from("*****@*****.**") contact_msg.add_to(request.POST.get('email')) sg.send(contact_msg) sending_msg = sendgrid.Mail() sending_msg.set_subject("Contact Request") sending_msg.set_html(message) sending_msg.set_text('Contact Request') sending_msg.set_from(request.POST.get('email')) sending_msg.add_to("*****@*****.**") sg.send(sending_msg) data = {'error': False, 'response': 'Contact submitted successfully'} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') else: errors = {} data = {'error': True, 'errinfo': validate_contact.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')
def send_email(from_address, from_name, to_address, subject, text, html, headers=None): msg = sendgrid.Mail(from_address=from_address, from_name=from_name, subject=subject, text=text, html=html) msg.add_to(to_address) if headers: msg.set_headers(headers) if settings.DEBUG: logger.debug("{sep}******{sep}{0}{sep}{1}{sep}******".format( msg.subject, msg.text, sep=os.linesep)) else: try: emailer.send(msg) except Exception as e: throw_ex = re_throw_ex(SMTPException, "Error sending email", e) if "find the recipient domain" in str(e).lower(): throw_ex = re_throw_ex(InvalidOutboundEmailError, "Invalid email", e) raise throw_ex[0](throw_ex[1]).with_traceback(throw_ex[2])
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 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 sendgrid_email(sender, to, subject, body, html, attachments=None): message = sendgrid.Mail(to=to.split(','), subject=subject, html=html, text=body, from_email=sender) logging.info(SENDGRID.send(message))
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 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 _create_mail(self, email): """A helper method that creates mail for sending.""" if not email.recipients(): return False from_email = sanitize_address(email.from_email, email.encoding) recipients = [ sanitize_address(addr, email.encoding) for addr in email.recipients() ] mail = sendgrid.Mail() mail.add_to(recipients) mail.add_cc(email.cc) mail.add_bcc(email.bcc) mail.set_text(email.body) mail.set_subject(email.subject) mail.set_from(from_email) if isinstance(email, EmailMultiAlternatives): for alt in email.alternatives: if alt[1] == "text/html": mail.set_html(alt[0]) for attachment in email.attachments: if isinstance(attachment, MIMEBase): mail.add_attachment_stream(attachment.get_filename(), attachment.get_payload()) elif isinstance(attachment, tuple): mail.add_attachment_stream(attachment[0], attachment[1]) return mail
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 __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 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 use_sendgrid(bot, update, email_address): chat_id = str(update.message.chat_id) html_message = '<b>Enjoy!</b>' message = sendgrid.Mail() message.add_to(email_address) message.set_subject('your filtered photos') message.set_html(html_message) # message.set_text('Body') message.set_from('telegram_filter_bot') message.add_attachment('filtered.jpg', open(chat_id + '/filtered.jpg', 'rb')) # message.add_attachment('filtered.jpg', open(chat_id+'/filtered.jpg', 'rb')) # message.add_attachment('sepia.jpg', open(chat_id+'/sepia.jpg', 'rb')) # message.add_attachment('inverted.jpg', open(chat_id+'/inverted.jpg', 'rb')) status, msg = sg.send(message) print(status, msg) if status == 200: success_msg = "<b>Your photos have been emailed successfully!</b>\n" bot.sendMessage(update.message.chat_id, text=success_msg, parse_mode="HTML") else: fail_msg = "<b>There was a problem emailing your photos...</b>\n" bot.sendMessage(update.message.chat_id, text=fail_msg, parse_mode="HTML")
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 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)
def send_messages(self, email_messages): email_message = email_messages[0] message = sendgrid.Mail( to=email_message.to, subject=email_message.subject, html=email_message.alternatives[0][0], from_email=email_message.from_email, from_name=self.get_from_name(email_message.from_email), ) for attachment in email_message.attachments: message.add_attachment_stream(attachment[0], attachment[1]) try: status, msg = self.sg.send(message) except sendgrid.SendGridError: if not self.fail_silently: raise else: if status == 200: return { 'email': email_message.to[0], 'status': 'sent', 'reject_reason': None, }
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 send_email(to, subject, body, template='email/notification.html', link=None, link_text="Sign in"): """ Send an email using sendgrid. Usage: send_email('*****@*****.**', 'Hey from OK', 'hi') """ if not link: link = url_for('student.index', _external=True) html = render_template(template, subject=subject, body=body, link=link, link_text=link_text) message = sendgrid.Mail(to=to, from_name="Okpy.org", from_email="*****@*****.**", subject=subject, html=emailFormat(html), text=body) try: status, msg = sg.send(message) return status except (sendgrid.SendGridClientError, sendgrid.SendGridServerError, TypeError, ValueError): logger.error("Could not send email", exc_info=True) return
def send(name, email, subject, html): message = sendgrid.Mail() message.add_to('{}'.format(email)) message.set_subject(subject) message.set_html(html) message.set_from(config.from_header) status, msg = sg.send(message)
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 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 as_message(email): """ Takes a ``grapevine.emails.Email`` model and converts it into a ``sendgrid.Mail`` object. """ message = sendgrid.Mail() message.add_to(email.to) message.add_to(email.cc) message.add_bcc(email.bcc) message.set_text(email.text_body) message.set_html(email.html_body) message.set_subject(email.subject) message.set_from(email.from_email) message.set_replyto(email.reply_to) # Grapevine GUID message.add_unique_arg(EmailBackend.UNIQUE_ARG_NAME, email.guid) for variable in email.variables.all(): if not bool(variable.value): message.add_category(variable.key) else: if variable.key in EmailBackend.SIMPLE_VARIABLE_MAP.keys(): sendgrid_key = EmailBackend.SIMPLE_VARIABLE_MAP[ variable.key] message.add_filter(sendgrid_key, 'enabled', int(variable.value)) elif variable.key[:4] == 'utm_': message.add_filter('ganalytics', 'enabled', 1) message.add_filter('ganalytics', variable.key, variable.value) return message
def send(self): sg = sendgrid.SendGridAPIClient(api_key=self.context.sendgrid_api_key) markdowner = Markdown(extras=["tables"]) from_email = sendgrid.Email(self.context.from_email) body = [] for a in self.analyses: stale_days = (datetime.datetime.now(tz=a.last_change.tzinfo) - a.last_change).days if a.last_change else "Never updated" body.append(line_item_template.format(file_path=a.doc_name, file_link=a.file_link, changed_by=a.changed_by_email, stale_days=stale_days)) plain_text = body_template.format(item_list="\n".join(body), github_repo=self.context.github_repo, github_repo_root=self.context.github_repo_path, max_stale_days=self.context.doc_is_stale_after_days) html_text = markdowner.convert(plain_text) content_text = sendgrid.Content("text/plain", plain_text) content_html = sendgrid.Content("text/html", html_text + "\n" + css) recipients = list(map(lambda x: sendgrid.To(x), self.recipients)) mail = sendgrid.Mail(from_email, recipients, self.subject(), plain_text_content=content_text, html_content=content_html) response = sg.client.mail.send.post(request_body=mail.get()) if 300 > response.status_code >= 200: success(f"Successfully sent email to {', '.join(self.recipients)} regarding {len(self.analyses)} files", 2) else: error( f"Failed to send email to {', '.join(self.recipients)} regarding {len(self.analyses)} files: " f"{response.status_code} - {response.body}", 2)
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_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_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 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_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 send_mail(user, subject, template_name, context={}): context = context.copy() context["user"] = user context["profile"] = user.profile html = render_to_string("email/" + template_name + ".djhtml", context) try: text = render_to_string("email/" + template_name + ".djtxt", context) except TemplateDoesNotExist: text = strip_tags(html) if SG: message = sendgrid.Mail(subject=subject, html=html, text=text, from_email=settings.EMAIL_ADDRESS) if has_name(user): message.add_to("{first} {last} <{email}>".format( first=user.first_name, last=user.last_name, email=user.email)) else: message.add_to(user.email) status, msg = SG.send(message) logger.info("Sent '%s' email to %s (status %i)", template_name, user.email, status) else: logger.info("SendGrid not available. Generated email: %s", html)
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)