Execute Javascript of an email sended with python smtplib - javascript

I'm practicing emailing and I wanted to know if it's possible to execute Javascript code when you send and email using smtplib and email libs, and when your message contain HTML code ?
It seem that nothing append.
HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</div>
<p class='Test'>This is my first sentence</p>
<script type="text/javascript">
var list = document.querySelector('p.Test');
list.innerHTML = "I want to change it";
</script>
</body>
</html>
Python Code:
import smtplib
from email.message import EmailMessage
def ConnectServer(User, Pass, Host):
SMTPServer = smtplib.SMTP_SSL(Host)
SMTPServer.ehlo()
SMTPServer.login(User, Pass)
return SMTPServer
def SendMail(Server, src, dst, data):
msg = EmailMessage()
msg['From'] = src
msg['To'] = dst
msg['Subject'] = 'Test envoi python'
msg.add_alternative(data, 'html')
Server.send_message(msg, src, dst)
def main():
#Define email adresses
me = 'AN_EMAIL#MAIL.com'
me2 = 'AN_OTHER_EMAIL#mail.com'
Server = ConnectServer(me, 'PASS', 'smtp.gmail.com')
with open('HTML PATH HERE', 'r', encoding='utf8') as File:
data = File.read()
SendMail(Server, me, me2, data)
pass
if __name__ == '__main__':
main()
I hope it's clear.

As far as i know we cant , i also tried to do this, i wanted to include a search bar for the table content in mail.
"No. JavaScript won't work in mails. A cool way to implement this feature
would be to include an image that points to your server, where you generate
the weather report server side and render it as an image, and return it to
the client.
Note though that Gmail caches images and depending on when he does it that
might not be refreshed."
Source : https://www.quora.com/

Related

Send a variable from a python file, to javascript, and then to a separate HTML file?

I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop

How to communicate with python server from web browser?

I'm trying to send basic commands to a robot from a webbrowser.
The robot is connected to my network and it is running a simpleXMLRPC server as below:
import socket
from xmlrpc.server import SimpleXMLRPCServer
message = []
def py_setMsg(msg):
#global message
message.append(msg)
return "check"
def py_getMsg():
if len(message) > 0:
temp = str(message[-1])
message.pop(-1)
return temp
else:
return "(no message)"
hostname = socket.gethostname()
host = socket.gethostbyname(hostname)
port = 60050
server = SimpleXMLRPCServer((host, port))
server.register_function(py_setMsg, "ext_setMsg")
server.register_function(py_getMsg, "ext_getMsg")
print("XMLRPC Server started..")
server.serve_forever()
My robot checks the messages in the message list and executes the commands in the list one by one.
What I want is to be able to add these commands from a web browser. So basically I want a command to be added to the list in my python server when a button is pressed, something like this:
<html>
<head>
</head>
<body>
<button type="button" onclick="setMessage()">klik hier</button>
<script>
function setMessage(){
send command to my python server
}
</script>
</body>
</html>
Can anyone tell me how I can achieve this?

Eel.* is not a function

This is my first time trying something out with eel. I've got a python script with some functions and I'm trying to communicate with them using #eel.expose but it gives me a javascript error - main.html:10 Uncaught TypeError: eel.startEncryption is not a function
Here's my code:
<head>
<title>Undefined</title>
<link rel="stylesheet" href="w3pro.css">
<script type="text/javascript" src="/eel.js"></script>
<script>
function startEncryption(mode){
massage = document.getElementById("massage").value;
code = document.getElementById("code").value;
string = eel.startEncryption(mode, massage, code);
document.getElementById("result").innerHTML += string;
}
</script>
</head>
<body>
<header class="w3-panel">
<h1>Vigenere Encryption</h1>
</header>
<div class="w3-panel">
<span>Message:<input type="text" id="massage"></span>
<br>
<span>Code:<input type="text" id="code"></span>
<br>
<span>Encrypted/Decrypted:<input type="text" id="result" readonly></span>
<br>
<input type="button" value="Encrypt" onclick="startEncryption(1)">
<input type="button" value="Decrypt" onclick="startEncryption(2)">
</div>
</body>
import eel
eel.init('C:\\Users\\Fantomas\\Documents\\Programming\\cipher\\web')
eel.start('main.html')
#eel.expose
def startEncryption(mode : int, message : string, code : string):
if mode == 1:
ciphertext = encryptMessage(code, message)
elif mode == 2:
ciphertext = decryptMessage(code, message)
return ciphertext;
I've got the eel.js file in my directory
Modufy the of your to:
import eel
eel.init('C:\\Users\\Fantomas\\Documents\\Programming\\cipher\\web')
#eel.expose
def startEncryption(mode : int, message : string, code : string):
if mode == 1:
ciphertext = encryptMessage(code, message)
elif mode == 2:
ciphertext = decryptMessage(code, message)
return ciphertext;
eel.start('main.html')
put eel.start('main.html') after exposing all shared functions.
Looking for your comments.
Good Luck
Obviously, Not placing eel.start at the end of your code often causes the problem, But eel.init's position has nothing to do with this particualar issue.
I just wanted to tell you that sometimes, The issue is not with your py code itself, But rather with the part where you import eel into your html code, Remember, the eel.js is always generated wherever your eel.init folder has been specified as, So when importing your eel.js in your html code, Make sure its in that particular folder
For example, If you have specified a folder web in your py code:
PYTHON:
eel.init('web')
Then When you import eel in html, It must be like the following
<script src="./eel.js"></script>
NOTE: Here, The .html file is also in the web folder, And so eel.js is imported from the same directory.
So yeah, This often happens(Atleast to me) Make sure you didnt make a mistake while importing eel.js in your html code.

Webpy and javascript to reload content

Hi I am starting with web.py and there are still plenty of things I do not understand.
This one is really annoying.
I try to do a simple page by using web.py and javascript.
The idea is to display a random value on a div which is updated every second by a python function.
This is the code I am using:
import web
import random
def rnd():
return random.randint(0, 10)
render = web.template.render('templates', globals={'rndm':rnd})
urls = (
'/mhs(.*)', 'mhs',
'/(.*)', 'index',
)
app = web.application(urls, globals())
class reloader:
def GET(self):
return render.reloader(rnd)
class index:
def GET(self, name='Bob'):
return render.index(name)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
Then the reloader.html file:
$def with(rnd)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id='demo'>Status: ? </div>
<script type="text/javascript">
function UpdateLeds() {
var x = document.getElementById('demo');
x.innerHTML = "Status: $rndm()";
}
setInterval(UpdateLeds, 1000);
</script>
</body>
</html>
I expect the code to display a page with a random number in 0 to 10 refreshed every second.
However all I can get is a page which displays a static value (i.e: the first random number obtained by rnd).
However if I manually refresh the page, the value is updated as I expect.
I can't understand if the problem is in my code or in my understanding of the architecture. Can someone help me please?
If I change your javascript function to this, it works for me:
function UpdateLeds() {
var x = document.getElementById('demo');
var random = Math.floor((Math.random() * 10) + 1);
x.innerHTML = "Status: "+random;
}
I'm not sure exactly what you're trying to do with $def with(rnd) in your HTML. I think you might be mixing web.py python and javascript syntax (just a guess), but once the page gets rendered in the browser, the python isn't doing you any good, and you have to do what you want with pure javascript.
Here's a JSFiddle: https://jsfiddle.net/s7n6nxng/

How to make a JQuery routine write to a text file on a computer desktop?

I want to make a JQuery routine that can write information (append) to a text file that either exists or does not exists. If the file does not exists than it should create the file and if it does it should either append or start writing new data to the file. I think append would be the best choice for a file logger. So it must append the data to the file.
I found this code on the internet and am trying to work it around so that I can use it on my page to write information to a simple text file.
Question: How can I make the following code log to a file for download?
Below is the new code and how I read the page that was listed in the comments on how a logger in Java script should work. The code is not working and I am not really certain as to why.
I am not really certain as to how the download works either but if I can just get the logger to work I will be happy for the time being.
Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<script src="log4moz.js">
</head>
<script>
getLocalDirectory : function() {
let directoryService = Cc["#mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
// this is a reference to the profile dir (ProfD) now.
let localDir = directoryService.get("ProfD", Ci.nsIFile);
localDir.append("XULSchool");
if (!localDir.exists() || !localDir.isDirectory()) {
// read and write permissions to owner and group, read-only for others.
localDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0774);
}
return localDir;
}
let myFile = XULSchool.getLocalDirectory();
myFile.append("someFile.txt");
let formatter = new Log4Moz.BasicFormatter();
let root = Log4Moz.repository.rootLogger;
let logFile = this.getLocalDirectory(); // remember this?
let appender;
logFile.append("log.txt");
root.level = Log4Moz.Level["All"];
appender = new Log4Moz.RotatingFileAppender(logFile, formatter);
appender.level = Log4Moz.Level["All"];
root.addAppender(appender);
this._logger = Log4Moz.repository.getLogger("XULSchool.SomeObject");
this._logger.level = Log4Moz.Level["All"];
this._logger.fatal("This is a fatal message.");
this._logger.error("This is an error message.");
this._logger.warn("This is a warning message.");
this._logger.info("This is an info message.");
this._logger.config("This is a config message.");
this._logger.debug("This is a debug message.");
this._logger.trace("This is a trace message.");
</script>
<body>
<form id="addnew">
<input type="text" class="A">
<input type="text" class="B">
<input type="submit" value="Add">
</form>
</body>
</html>
#Smeegs says this nicely
Imagine a world where any website can edit files on your computer
JavaScript (or jQuery) cannot touch the user's file system.
Even if you find some hacked up thing that works via ActiveXObject, you should not attempt to do this. Cross-browser support would be very narrow for this feature.
If you want to write out file, just provide the user with a download.
If this is just a means of reading/writing some kind of data, look into localstorage.

Categories

Resources