I have a HTML page where there is one hyperlink. This html email will be sent to users via outlook (I have written the mail function using flask python) and when users will click on hyperlink on the email body, it will eventually open another page. This page will be same but, the content of the page will be different for different users based on the users' email id.
Right now, my requirement is to pass the user email ID through hyperlink so, I can display different content based on email ID. Can it be done through hyperlink? As, you know that outlook uses Microsoft Word as rendering engine so, will it be difficult to pass parameter through hyperlink ?
Or, can I pass the email ID through my flask function while sending the mails?
My flask function which will send mail to outlook is below
from flask import Flask, render_template
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='My Company SMTP MAIL SERVER',
MAIL_PORT=My Company SMTP PORT NUMBER,
# MAIL_USE_SSL=True,
MAIL_USERNAME='XXXXX.YYYY#mycompanyname.com',
)
mail = Mail(app)
#app.route('/')
def mailSend():
try:
recipeint_emails = fetch_recipient_emails
msg = Message("Send Mail Tutorial!",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=recipeint_emails)
msg.html = render_template('linkPage.html')
mail.send(msg)
return 'Mail sent!'
except Exception as e:
print(type(e))
print(e)
return 'error'
The linkPage.html will contain the hyperlink which is mentioned below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hyperlinkdemo</title>
</head>
<body>
Visit Dynamic Page
</body>
</html>
Any suggestion will be very helpful.
Flask has already a builtin function url_for to generate properly a link with extra parameters. Refer to this doc
UPDATE
it's recommended to choose the accurate name for routes
it's recommended to use snake_case when naming views
i recommend you to refer to the official Flask-Mail doc section Bulk Mail
#app.route('/bulk-email')
def bulk_mail():
[..]
# Get all users first
with mail.connect() as conn:
for user in users:
msg = Message(subject="Tutorial",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=[user.email])
# pass dynamically the user to the template
msg.html = render_template('linkPpage.html', user=user)
conn.send(msg)
in linkPage.html template you can do
<p>Dear {{ user.username }},</p>
<p>
Open Link tutorial
</p> //added double quotation
you have to implement the logic of link_tutorial function, when user click on the link it will be redirected to your app to show him a customized page / tutorial:
#app.route('/link-tutorial/<int:user_id>')
def link_tutorial(user_id):
# fetch the user with the given user_id and render the right template for him.
[..]
return render_template('tutorial.html')
finally, i would recommend you using celery an asynchronous task queue to handle the bulk email more efficiently than Flask-Mail, because sending mail is a blocking task and your app will be very slow and not responsive.
Related
I want to validate file. While file is invalid, i want to refresh my page and inform user that he did not upload proper file. So i have this in my
views/campaign.py
try:
wb = load_workbook(mp_file)
except BadZipfile:
return redirect('campaign_add', client_id)
The only way i know how to do it is add another attribute to client class which will be
is_error(models.BooleanField())
And then change views/campaign to
try:
client.is_error = False
wb = load_workbook(mp_file)
client.save()
except BadZipfile:
client.is_error = True
client.save()
return redirect('campaign_add', client)
And with another attribute i can add in my campaign.html file some kind of if is.error is true i'm adding some kind of windows with information about bad file after reloading page. But is there any way to do it without adding another attribute?
Ok, let's imagine that the answer is a little bit complicated than you've expected.
Modern UI's are not reloading pages just to inform about some errors with user input or upload.
So what is the best user experience here?
User is uploading some file(s) from the page.
You are sending a file via JavaScript to the dedicated API endpoint for this uploading. Let's say /workbook/uploads/. You need to create a handler for this endpoint (view)
Endpoint returns 200 OK with the empty body on success or an error, let's say 400 Bad Request with detailed JSON in the body to show to the user what's wrong.
You're parsing responses in JavaScript and show the user what's wrong
No refreshes are needed. 🙌
But the particular answer will need more code from your implementation. (view, urls, template)
So, I'm currently using A system where I can manually say if the website is online or not; but I don't see this as "Efficient" because I won't be there 24/7. So I was wondering if there was a way to check if their website is online or not and then create a file on a server as soon as it goes down?
You can use free service like UptimeRobot. It will send you notification when the site is down or back up.
I wrote simple script in python. Script simple check website status.
Here is a link, maybe help You.
Script simple check site code response. If status code is ok - 200 then do nothing. If status code is different than 200, send email notification to declared addresses in config.ini.
Finaly, in crontab I create a log file with site statuse.
1 * * * * /usr/bin/python3 /scripts/WebPageStatusCheck/main.py >> /scripts/WebPageStatusCheck/log/WebPageStatusCheck.log 2>&1
Here check page status and return site status to main.py
import urllib.request
class CheckSiteStatus:
def __init__(self):
pass
#staticmethod
def check_site_url(url: str):
url = 'http://' + url
status = urllib.request.urlopen(url).getcode()
return status
With best regards!
You check it using
1:Ping your website
2:Go here and enter your website url to check availability
Make sure that your site is live on server.
Depends on the technology you are using for your website, you can program events when site goes up or down. Look at this for example of shutdown event in ASP.NET.
I cannot understand how this works:
from flask import Flask, redirect
oauth_uri = 'https://accounts.freelancer.com/oauth/authorise'
client_id = '<CLIENT_ID>'
redirect_uri = '<CLIENT_REDIRECT_URI>'
prompt = 'select_account consent'
advanced_scopes = '1 3'
app = Flask(__name__)
# Users who hit this endpoint will be redirected to the authorisation prompt
#app.route('/authorize')
def handle_authorize():
return redirect(
'{0}?response_type=code'
'&client_id={1}&redirect_uri={2}'
'&scope=basic&prompt={3}'
'&advanced_scopes={4}'.format(
oauth_uri, client_id, redirect_uri, prompt, advanced_scopes
)
)
This code gives me : Invalid redirect URI in browser.
Whats this redirect URI, why can't I give any redirect uri of my choice?
Its documented here: can anyone please explain to me how this works,
https://developers.freelancer.com/docs/authentication/generating-access-tokens#header-receive-authorisation-response
The redirect URL is the URL you set for your application on your apps dashboard. You need to specify a valid URL for Freelancer.com to redirect to after the user has granted access for your app. Think of how Facebook grants access to third party apps using their log in system.
I am trying to get the url of an image attachment published by a facebook page. The goal is to embed that image in a webpage in order for the website to always display the last image attachment published by the page. I own both website and FB page.
I have yet not grasped all the details on handling Facebook Graph API, but here is what I did so far:
1) in FB developers website, I have created an application, getting its App ID and secret;
2) I used that information to get an access token (just pasted in my browser the following code:
https://graph.facebook.com/oauth/access_token?client_id={my-client-id}&client_secret={my-client-secret}&grant_type=client_credentials
3) in my website, I have loaded Facebook JS SDK after the body tag; and got also my Facebook page ID from Facebook Page administration;
4) now the real question begins: how can I query Facebook to get the information that I need – the source url of the last published image?
The best result I have gotten so far was by making a getJSON call with the help of jQuery:
var fbfeed = $j.getJSON('https://graph.facebook.com/{my-page-id}/feed?access_token={my-token}&fields=attachments&limit=1');
This will get and store a JSON array in the fbfeed variable (please correct me if I'm wrong). One of the keys of that array is called "src" which contains the source url of the attachment – the information I need to embed that picture in my website;
I have the following problems / concerns:
- I have not found the way to retrieve the value of the "url" key – how can I do that? How can I parse the fbfeed variable and extract the value of the "url" key?
– I have concerns with my usage of the access token:
is it problematic to expose the access token in this way, by using it in a jQuery function? Is it a security risk? If so, can I "mimic" this request but using a server side language such as PHP?
Will this access token expire (i.e. will I need to repeat step 2 from time to time?). So, imagining that I can get this to work, will I need from time to time to "refresh" the access token?
Thanks for your help.
I have managed to get the information I needed using server-side code, although it may not be the most "clean solution": it will iterate through the last 5 posts of my page until it finds an image and a post url:
<?php
$url = 'https://graph.facebook.com/{page-id}/feed?access_token={access-token}&fields=attachments,link&limit=5';
$json = file_get_contents($url);
$json_data = json_decode($json, true);
for($count = 0; $count < 5; $count++) {
$imagesource = $json_data['data'][$count]['attachments']['data'][0]['media']['image']['src']; // gets the image url
$postlink = $json_data['data'][$count]['link']; // gets the post url
if (isset($imagesource) && isset($postlink)) {
// do stuff with the image and post url
break;
};
};
// then I can do other stuff as fallback if the image url and post url are not found
My application is meant to speed up the retrieval of phone call information from our telephone system.
The best way to get this information is to create a new search on the telephone system's web interface and export the results to an Excel spreadsheet which my application then imports into a DataSet.
To get the export, from the login screen, the process goes as follows:
Log in
Navigate to Reports Page
Click "Extension Detail" link
Select "Extensions" CheckBox
Select the extensions (typically all the ones currently being used) from the listbox
Specify date range
Click on Export button
It's not a big job to do it manually every day, but, for reliability, it would be great if I can make my application do this automatically the first time it starts every day.
Since more than 1 person in the company is going to use this application, having a Windows Service do it would be even better.
I don't know if it'll help, but the system is Datatex Topaz Next Generation telephone management system: http://www.datatex.co.za/downloads/index.html#TNG
Can anyone give me a basic idea how to do this?
Also, can anyone post links (in comments if need be) to pages where I can learn more about how to do this?
I have done the something similar to fetch info from a website. I cannot give you a exact answer. But the idea is to send login info to the page with form values. If the site is relying on cookies, you can use this cookie aware WebClient:
public class CookieAwareWebClient : WebClient
{
private CookieContainer cookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = cookieContainer;
}
return request;
}
}
You should be aware that some sites rely on a session id being passed so the first thing I did was to fetch the session id from the page:
var client = new CookieAwareWebClient();
client.Encoding = Encoding.UTF8;
var indexHtml = client.DownloadString(*index page url*);
string sessionID = fetchSessionID(indexHtml);
Then I had to log in to the page which you can do by uploading values to the page. You can see the specific form elements with "view source" but you have to know a little HTML to do so.
var values = new NameValueCollection();
values.Add("sessionid", sessionID); //Fetched session id
values.Add("brugerid", args[0]); //Username in my case
values.Add("adgangskode", args[1]); //Password in my case
values.Add("login", "Login"); //The login button
//Logging in
client.UploadValues(*url to login*, values); //If all goes perfect, I'm logged in now
And then I could download the page I needed. In your case you may use DownloadFile(...) if the file always have the same url (something like Export.aspx?From=2010-10-10&To=2010-11-11) or UploadValues(...) where you specify the values as before but saves the result.
string html = client.DownloadString(*url*);
It seems you have a lot more steps than I did. But the principle is the same. To see what values your send to the site to login etc. you can use programs such as Fiddler (windows) which can capture the activity going on. Essential you just do exactly the same thing but watch out for session id etc. which is temporary.
The best idea is really to use some native way to fetch data, but if don't got the code, database etc. you have to do it the ugly way. You may also need a HTML parser to fetch the data (ups, you don't because you export to a file). And last but not least, keep in mind that pages can change and there is great potential to fail to login, parse etc.
Please ask for if you are uncertain what is going on.
ADDITION
The CookieAwareWebClient is not my code:
http://code.google.com/p/gardens/source/browse/Montrics/Physical.MyPyramid/CookieAwareWebClient.cs?r=26
Using CookieContainer with WebClient class
I also found some relevant threads:
What's a good tool to screen-scrape with Javascript support?
http://forums.asp.net/t/1475637.aspx
With a HTTP client, you need to do the following:
Log in, using cookies or HTTP authentication
Request a page
Submit form data
This means that you need some class or component in your program that can do HTTP, cookies, authentication and forms. With this, you do the same requests a user would do.