def email_sender(sender, instance, **kwargs): Email_subscribers = EmailSubscribers.objects.all() msg = Emails.objects.latest('email') ms = msg.email for email_subscriber in Email_subscribers: email = email_subscriber.email message = Mail( from_email='*****@*****.**', to_emails=email, subject='Newsletter subscription', html_content=ms, ) try: sg = SendGridAPIClient( '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' ) response = sg.send(message) # print(response.status_code) # print(response.body) # print(response.headers) except Exception as e: print('not working')
def contactMap(request): successMail = False recaptchaFailed = False recaptch = False # find the settings linked with user # if no linked settings item exist if request.method == 'GET': # if user is logged in, fields are automatically filled in. if not request.user.is_authenticated: form = ContactFormNotLogin() recaptch = True else: form = ContactForm(request.user) else: # post function executed when the user clicks send. if not request.user.is_authenticated: recaptch = True form = ContactFormNotLogin(request.POST) #Recaptcha check for users that are not logged in recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.RECAPTCHA_PRIVATE_KEY, 'response': recaptcha_response } r = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if not result['success']: recaptchaFailed = True else: form = ContactForm(request.user, request.POST) if form.is_valid(): #when all mandatory fields have been filled out subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = { 'first_Name': form.cleaned_data['firstName'], 'name': form.cleaned_data['lastName'], 'subject': form.cleaned_data['subject'], 'text': form.cleaned_data['message'], 'tel': form.cleaned_data['phone'], 'mail': form.cleaned_data['from_email'] } #collects information from the form to pass to email htmlcontend = get_template('emailTamplate.html').render( message) #formats/creates email message = Mail(from_email='*****@*****.**', to_emails=settings.CONTACT_RECEIVERS, subject=subject, html_content=htmlcontend) sg = SendGridAPIClient(settings.EMAIL_HOST_PASSWORD) response = sg.send(message) successMail = True return render( request, 'mapContact.html', { 'form': form, "recaptcha": recaptch, 'successMail': successMail, 'recaptchaFailed': recaptchaFailed })
def send_email(routes_to_report): """Send email using sendgrid.""" number_of_routes = len(routes_to_report) if number_of_routes == 0: return False formatted_date = dt.datetime.utcnow().strftime("%A, %b %d") rich_email_body = render_template("email.html", routes=routes_to_report, date=formatted_date) sg = SendGridClient(config.SG_USERNAME, config.SG_PASSWORD, raise_errors=True) formatted_time = dt.datetime.utcnow().strftime("%F %T") subject = '({}): {} routes' subject = subject.format(formatted_time, number_of_routes) try: message = Mail(to=config.TO_EMAIL, subject=subject, html=rich_email_body, from_email=config.FROM_EMAIL) status, msg = sg.send(message) return msg except SendGridClientError as e: print 'Failed to send email: ', e raise
def forgot_password(): if request.method == 'POST': email = request.form['email'] user = Account.query.filter_by(email=email).first() print(user.hash_email) if user is not None: # send an email link = "http://127.0.0.1:5000/reset/" + user.hash_email message = Mail( from_email='*****@*****.**', to_emails=[email], subject="Password Reset", html_content= "This is your link to reset your password (copy and paste whole link): " + link) # reset/hashed email for security sg.send(message) return redirect( url_for( 'success', message= "Success! An email of confirmation has been sent to you. " "Click on the link attached to change your password.")) return render_template('forgot.html')
def index(self): if request.method == 'GET': user_emails = db.session.query(User).filter( User.new_features_subscription == True) email_list = [] for user in user_emails: email_list.append(user.email) email_list.append(';') context = {'user_emails': email_list} return self.render('sendemail.html', **context) else: jsondata = request.get_json(force=True) users_send_email_to = db.session.query(User).filter( User.new_features_subscription == True) message = Mail() message.set_subject(jsondata['subject'].encode("utf8")) message.set_text(jsondata['message'].encode("utf8")) message.set_from('ANYWAY Team <*****@*****.**>') for user in users_send_email_to: message.add_bcc(user.email) try: sg.send(message) except SendGridClientError: return "Error occurred while trying to send the emails" except SendGridServerError: return "Error occurred while trying to send the emails" return "Email/s Sent"
def _send_eos(results, run_time): subject = '[DNStats] Scan Ending' print("taco") print(run_time) result_count = db_session.query( models.SiteRun).filter_by(run_id=run_time).count() print("result_count: " + str(result_count)) body = ''' End time: {starting_time} Number results: {result_count} Run id: {run_id} DNStats scan has ended. '''.format(starting_time=datetime.datetime.now().strftime('%c'), result_count=result_count, run_id=run_time) message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=subject, plain_text_content=body) _send_message(message) print("body: " + body)
def _send_botched_deploy(date, run_id: int, count: int, target_count: int) -> None: """ Send a email stating not enough sites have been scanned :param date: start date of the scan :param run_id: database id of the scan :param count: number of sites that have been complted in the scan :param target_count: the target number of scans, below this numbet the deployment will be refused :return: None """ delta = target_count - count subject = '[DNStats] CRITICAL Botched Website Deploy' body = ''' Run id: {run_id} Target: {target_count} Actual = {count} Delta = {delta} Run start Time = {starting_time} Cowardly refusing to deploy run {run_id}, it appears the scan failed or is not finished. Investigate and publish results. '''.format(starting_time=date.strftime('%c'), run_id=run_id, target_count=target_count, count=count, delta=delta) message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=subject, plain_text_content=body) _send_message(message)
def send(**kwargs): print('sending message') print(_green(kwargs)) result = True body = Content( "text/html", loader.render_to_string(kwargs.get('email_template'), kwargs.get('context'))) try: message = Mail(from_email=settings.SENGRID_SENDER_EMAIL, to_emails=kwargs.get('to_email'), subject=kwargs.get('subject'), html_content=body) sengrid_email = SendGridAPIClient(api_key=settings.SENDGRID_API_KEY) email_request = sengrid_email.send(message) print(_green('----------- sendgrid email response -----------')) print(email_request.status_code) print(email_request.body) print(email_request.headers) print(_green('----------- sendgrid email response -----------')) except Exception as e: result = False if not settings.DEBUG: slack_messages.run( msg='Error sending email to {} : Error: {}'.format( kwargs.get('to_email'), str(e)), channel_id=settings.SLACK_BUGS_CHANNEL_ID) print(_red('Error sending email caused by : {}'.format(str(e)))) return result
def send_email(email_params): if is_local(): # localhost (not really sending the email) print("***********************") print( "You are on localhost, so no e-mail will be sent. This is message:" ) print(email_params["message_body"]) print("+++++++++++++++++++++++") else: # production (sending the email via SendGrid) # SendGrid setup sg = SendGridAPIClient(api_key=os.getenv("SendGrid-Mail")) # E-mail setup sender_email = os.getenv("APP_EMAIL") recipient = email_params["recipient_email"] subject = email_params["message_title"] msg_html = email_params["message_html"] email_message = Mail(from_email=sender_email, to_emails=recipient, subject=subject, html_content=msg_html) try: response = sg.send(email_message) logging.info(response.status_code) logging.info(response.body) logging.info(response.headers) except Exception as e: logging.error(str(e))
def email_twets(email): mail = Mail(from_email='*****@*****.**', to=email, subject='Tweets', text=str(list(tweets.find()))) sg.send(mail) return jsonify({})
def sendgrid_email(email, name): body = 'Hi,' + name message = Mail(from_email='*****@*****.**', to_emails=email, subject=SUBJECT, plain_text_content=body) response = sg.send(message)
def send_activation_email(data): message = Mail(from_email=EMAIL_SENDER, to_emails=data['to_email'], subject=data['subject'], html_content=data['message']) sg = SendGridAPIClient(SENDGRID_KEY) sg.send(message)
def send_email(report, title): API_KEY = os.environ.get('SENDGRID_KEY') if API_KEY is None: print 'No SendGrid API key found! Please set the SENDGRID_KEY env var' sys.exit(1) sg = SendGridClient(API_KEY, raise_errors=True) # Backwards compatability for emails stored as strings, not lists emails = report['project_details']['email'] if type(emails) is not list: emails = [emails] for address in emails: message = Mail() message.add_to(address) message.set_subject(title) message.set_html(generate_email_text(report)) message.set_from('STACKS <*****@*****.**>') try: sg.send(message) except SendGridError as e: print e except SendGridClientError as e: print e except SendGridServerError as e: print e
def publish_diff(self, diff, feed_config): if diff.emailed: raise AlreadyEmailedError(diff.id) elif not (diff.old.archive_url and diff.new.archive_url): raise ArchiveUrlNotFoundError() api_token = feed_config.get("api_token", self.api_token) sender = feed_config.get("sender", self.sender) receivers = feed_config.get("receivers", self.receivers) if not all([api_token, sender, receivers]): raise ConfigNotFoundError subject = self.build_subject(diff) message = Mail( from_email=sender, to_emails=receivers, subject=subject, html_content=self.build_html_body(diff), ) try: self.mailer(api_token).send(message) diff.emailed = datetime.utcnow() logging.info("emailed %s", subject) diff.save() except Exception as e: logging.error("unable to email: %s", e)
def send_informing_about_comment_email(news_author_id, comment_author_id, news_id, domain): UserModel = get_user_model() try: news_author = UserModel.objects.get(pk=news_author_id) comment_author = UserModel.objects.get(pk=comment_author_id) message = render_to_string( 'informing_about_comment_mail.html', { 'news_author': news_author, 'comment_author': comment_author, 'domain': domain, 'news_id': news_id }) message = Mail( from_email='*****@*****.**', to_emails=news_author.email, subject='К вашемей новости на сайте {} оставлен комментарий'. format(domain), html_content=message) sg = SendGridAPIClient(SEND_GRID_API_KEY) sg.send(message) except UserModel.DoesNotExist: pass except Exception as e: print(e)
def send_message(self, message='', **kwargs): subject = kwargs.get(ATTR_TITLE) from sendgrid import Mail mail = Mail(from_email=self.sender, to=self.recipient, html=message, text=message, subject=subject) self._sg.send(mail)
def post(self, request, *args, **kwargs): print(request.POST) # create the user ticket user_obj = Profile.objects.get(user=request.user) company_obj = Company.objects.get( name__iexact=request.POST.get("company")) SupportTickets.objects.create( user=user_obj, title=request.POST.get("title"), content=request.POST.get("message"), ticket_id=random_string_generator(7), affected_company=company_obj, slug=random_string_generator(20), ) # send mail to system core.. sg = SendGridAPIClient(email_settings.SENDGRID_API_KEY) message = Mail( from_email=email_settings.DEFAULT_FROM_EMAIL, to_emails=email_settings.SUPPORT_EMAIL, subject="A New Ticket Was Opened!", html_content= "A support ticket has been opened please confirm and attend to all opened tickets." ) sg.send(message) return JsonResponse({"message": "Ticket Created Successfully!"})
def send_email(email, code): body = "my code =" + code message = Mail(from_email="*****@*****.**", to_emails=email, subject=subject, plain_text_content=body) print(email, code) response = sg.send(message)
def test_send(self): m = Mail() m.add_to('John, Doe <*****@*****.**>') m.set_subject('test') m.set_html('WIN') m.set_text('WIN') m.set_from('*****@*****.**') m.set_asm_group_id(42) m.add_cc('*****@*****.**') m.add_bcc('*****@*****.**') m.add_substitution('subKey', 'subValue') m.add_section('testSection', 'sectionValue') m.add_category('testCategory') m.add_unique_arg('testUnique', 'uniqueValue') m.add_filter('testFilter', 'filter', 'filterValue') m.add_attachment_stream('testFile', 'fileValue') url = self.sg._build_body(m) url.pop('api_key', None) url.pop('api_user', None) url.pop('date', None) test_url = json.loads(''' { "to[]": ["*****@*****.**"], "toname[]": ["John Doe"], "html": "WIN", "text": "WIN", "subject": "test", "files[testFile]": "fileValue", "from": "*****@*****.**", "cc[]": ["*****@*****.**"], "bcc[]": ["*****@*****.**"] } ''') test_url['x-smtpapi'] = json.dumps( json.loads(''' { "sub": { "subKey": ["subValue"] }, "section": { "testSection":"sectionValue" }, "category": ["testCategory"], "unique_args": { "testUnique":"uniqueValue" }, "filters": { "testFilter": { "settings": { "filter": "filterValue" } } }, "asm_group_id": 42 } ''')) self.assertEqual(url, test_url)
def send_invite_member(from_user, to_email, token, message_text): message = Mail(from_email=os.environ.get('FROM_EMAIL'), to_emails=to_email) message.template_id = 'd-d1fc8d063c1c464792606f70fe6acfbf' message.dynamic_template_data = { 'inviter_name': from_user.first_name, 'message': message_text, 'url': 'http://localhost:3000/invitation?token=' + token } sg.send(message)
def welcome_email(user): message = Mail(from_email=from_email, to_emails=user.email) message.template_id = 'd-a97bb89a6bfe44fda4deba762ef6a424' message.dynamic_template_data = { 'name': user.first_name, 'url': base_url + '/confirm-email?token=' + user.email_verification_token } sg.send(message)
def send_email(email,code): body = 'best code='+code message = Mail( from_email='*****@*****.**', to_emails=email, subject=SUBJECT, plain_text_content=body, ) response = sg.send(message)
def build_mail(user): return Mail( from_email=SENDER_EMAIL, to_emails=user.email, subject=f'{user.personaname},为 SYSUPause 群组验证该邮箱', html_content= (f'<strong>Steam 用户 {user.personaname} ({user.profileurl}) 正在尝试使用你的邮箱进行认证: </strong><br/>' f'<strong>请点击以下链接完成 SYSUPause 邮箱验证,验证有效期为 30 分钟:</strong><br/>' f'<a href="{user.get_verify_link()}">{user.get_verify_link()}</a>'))
def send_email_verification(user_id, resend=False): if not Configuration.PUSH_ENABLED: return sendgrid = create_sendgrid() user = User.find(user_id) verify_code = wigo_db.get_new_code({ 'type': 'verify_email', 'user_id': user_id, 'email': user.email }) verify_link = '{}://{}/c/{}'.format( 'https' if Configuration.ENVIRONMENT != 'dev' else 'http', Configuration.WEB_HOST, verify_code) logger.info('generated verify code for user "%s", "%s"' % (user.email, verify_code)) first_name = user.first_name if not first_name: first_name = user.email msg = Mail() if resend: msg.set_subject('Everyone deserves a second chance') else: msg.set_subject('Welcome to Wigo') msg.set_from('Wigo <*****@*****.**>') if user.first_name and user.last_name: msg.add_to('%s <%s>' % (user.full_name, user.email)) else: msg.add_to(user.email) msg.set_text( "Hi %s\n\nPlease click the following link to verify your email address:\n\n%s\n\n" % (first_name, verify_link)) msg.set_html( render_template('confirmation_email.html', name=first_name, confirmation_link=verify_link, resend=resend)) msg.add_unique_arg('user_id', user.id) msg.add_category('verify') msg.add_filter('opentrack', 'enable', 0) msg.add_filter('subscriptiontrack', 'enable', 1) msg.add_filter('subscriptiontrack', 'replace', '-UNSUB-') sendgrid.send(msg) logger.info('sent verification email to "%s"' % user.email)
def forgot_password(user): message = Mail(from_email=os.environ.get('FROM_EMAIL'), to_emails=user.email) message.template_id = 'd-f626293dd98649d6b6d53a5aa3a355d4' message.dynamic_template_data = { 'name': user.first_name, 'url': base_url + '/reset-password?token=' + user.password_reset_token } sg.send(message)
def send(sender_mail, send_to, subject, html, text=None): client = SendGridClient(current_app.config.get('SENDGRID_USERNAME'), current_app.config.get('SENDGRID_PASSWORD')) message = Mail() message.set_from(sender_mail) message.add_to(send_to) message.set_subject(subject) message.set_html(html) message.set_text(text) client.send(message)
def send(self): mail = Mail( from_email=self.from_email, to_emails=self.to_email, subject=self.title, html_content=self.content, ) response = self.send_grid.client.mail.send.post( request_body=mail.get())
def sendEmail(sender, recipient, subject, html, text): sg = SendGridClient('ecpf', 'Iheart1!', secure=True) message = Mail() message.set_subject(subject) message.set_html(html) message.set_text(text) message.set_from(sender) message.add_to(recipient) sg.send(message) return True
def sendgrid_email_emma(): with open('emma.txt', 'r') as f4: emma_list = f4.readlines() for line in emma_list: body = line message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=SUBJECT, plain_text_content=body) response = sg.send(message)
def sendgrid_email_steven(): with open('stev.txt', 'r') as f5: steven_list = f5.readlines() for line in steven_list: body = line message = Mail(from_email='*****@*****.**', to_emails='*****@*****.**', subject=SUBJECT, plain_text_content=body) response = sg.send(message)