This is my code it should send me an email with a screenshot but instead I get the following error.
Traceback (most recent call last):
File "email_screenshot.py", line 34, in <module>
my_screenshot.start()
File "email_screenshot.py", line 26, in start
with open(im) as file:
TypeError: coercing to Unicode: need string or buffer, PngImageFile found
This is the code what should I do to get rid of the type error in this python2.7 code.
import pyscreenshot as ImageGrab
import smtplib
import base64
class Screenshot:
def __init__(self, email, password):
self.screenshot = ImageGrab.grab
self.email = email
self.password = password
def send_screenshot(self):
self.send_email(self.email, self.password, self.screenshot)
report = self.send_screenshot
report.start()
def send_email(self, email, password, message):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(email, password)
server.sendmail(email, email, message)
server.quit()
def start(self):
im = ImageGrab.grab()
with open(im) as file:
file.write(base64.b64decode(im))
with im:
self.send_screenshot()
im.join()
my_screenshot = Screenshot("myuser", "mypass",)
my_screenshot.start()
does anyone have any ideas
Related
I am a beginner trying to send a personalized email using Python. I need to send a numerical code along with the message, and I'm using this code.
import smtplib
import ssl
def send_email(receive, pCode):
port = 465
sender = "mail#gmail.com"
password = "passw"
receive = sender # For test purposes
recipients = [{"receive": receive, "pCode": pCode}] # Also for test purposes
message = """
Subject: SUBJ
CODE:
{pCode}
"""
context = ssl.create_default_context()
print("Starting to send")
with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server:
server.login(sender, password)
for recipient in recipients:
server.sendmail(sender, recipient["receive"], message.format(pCode=pCode))
print("email sent")
send_email("receive#gmail.com", '123456')
But when I run it, I get this error.
Traceback (most recent call last):
File "C:/MyPythonScripts/Iubi/PythonApps/emailSender.py", line 54, in <module>
send_email("receive#gmail.com", '123456')
File "C:/MyPythonScripts/Iubi/PythonApps/emailSender.py", line 48, in send_email
server.sendmail(sender, recipient["receive"], message.format(pCode=pCode))
File "C:\Users\Francesco Cambria\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 859, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe8' in position 95: ordinal not in range(128)
I really have tried everything, I've added # encoding=utf8
on top of my file, I've tried with pCode = pCode.encode('utf8') and some other solutions I found on stack overflow, but none seem to work, I'm getting always the same error.
you can encode the message yourself like:
server.sendmail(sender, recipient["receive"], message.format(pCode=pCode).encode('utf-8'))
The following code just returns the output: "Failed to open WebSocket" Please help me correct it. I suspect the ws_url might be faulty, but still unsure.
from ws4py.client.threadedclient import WebSocketClient
import base64, time
class SpeechToTextClient(WebSocketClient):
def __init__(self):
ws_url = "wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
username = "your username"
password = "your password"
auth_string = "%s:%s" % (username, password)
base64string = base64.b64encode(auth_string.encode())
try:
WebSocketClient.__init__(self, ws_url,
headers=[("Authorization", "Basic %s" % base64string)])
self.connect()
except: print("Failed to open WebSocket.")
def opened(self):
self.send('{"action": "start", "content-type": "audio/l16;rate=16000"}')
def received_message(self, message):
print(message)
stt_client = SpeechToTextClient()
time.sleep(3)
stt_client.close()
Error message is provided below:ยจ
Here is the full error message:
Traceback (most recent call last):
File "C:\Users\Vetle\Desktop\Python projects\problem.py", line 27, in
stt_client.close()
File "C:\Users\Vetle\AppData\Local\Programs\Python\Python35\lib\site-packages\ws4py\client__init__.py", line 205, in close
self._write(self.stream.close(code=code, reason=reason).single(mask=True))
File "C:\Users\Vetle\AppData\Local\Programs\Python\Python35\lib\site-packages\ws4py\websocket.py", line 283, in _write
raise RuntimeError("Cannot send on a terminated websocket")
RuntimeError: Cannot send on a terminated websocket
As per the API documentation you need to pass in an authentication token and not the basic service credentials. The Documentation has sample web socket code - https://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#recognize_audio_websockets
This code is "suppose" to send an email.
import smtplib
#SERVER = "localhost"
FROM = 'myEmail#email.com'
TO = ["toEmail#email.com"] # must be a list
SUBJECT = "Hello!"
TEXT = "This message was sent with Python's smtplib."
# Prepare actual message
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP('myserver')
server.sendmail(FROM, TO, message)
server.quit()
I get this error message.
Traceback (most recent call last):
File "C:\Users\myCpu\Documents\myFiles\python\test wy.py", line 1, in <module>
import smtplib
File "C:\Python27\lib\smtplib.py", line 46, in <module>
import email.utils
File "C:/Users/myCpu/Documents/myFiles/python\email.py", line 5, in <module>
ImportError: No module named mime.text
Using:
Python 2.7
Windows 7 Professionnal
Gmail (#gmail.com)
Can anyone help me with this code?
This is what I did for gmail.
Hope this sloves your problem
from email.mime.text import MIMEText
def construct_mesage():
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string())}
Rename the file you are working on named email.py to something else. It is likely breaking imports in your libraries.
I am trying to use jython code from JIRA post function
I have create a file called foo,py and placed into jython Lib directory
foo.py looks like
from email.MIMEText import MIMEText
from smtplib import SMTPException
from smtplib import SMTP
class my_mail(object):
def spam(subj, to, body):
msg = MIMEText(body, 'html')
msg['Subject'] = subj
msg['To'] = to
msg['Importance'] = 'high'
sender = 'abd#abd.com'
passwd = 'password'
s = SMTP('smtp.office365.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(sender, passwd)
s.sendmail(sender, [to], msg.as_string())
s.quit()
The calling program looks like
to = 'abcd#bad.com'
sub = " test "
body " some body"
import foo
nmail = foo.my_mail()
nmail.spam(subj, to, body)
With this, I always get error
root cause:
Traceback (most recent call last): File "<string>", line 35, in <module> File "/usr2/atlassian/application-data/jira/jss/jython_2.5.2/Lib/foo.py", line 18, in spam s.starttls() NameError: global name 'server' is not defined
No matter what I do, it is always line 18 in foo.py :-(
This foo.py works fine, if I use command line python with same function call.
Any suggestions?
I am trying to send a message on facebook chat with sleekXMPP, using the answer from here as a boilerplate: Send a Facebook Message with XMPP using Access Tokens in Python
My code is
import sleekxmpp
class SendMsgBot(sleekxmpp.ClientXMPP):
def init(self, jid, recipient, message):
print "..."
sleekxmpp.ClientXMPP.__init__(self, jid, 'ignore')
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start, threaded=True)
def start(self, event):
self.send_presence()
self.get_roster()
self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
self.disconnect(wait=True)
if __name__ == "__main__":
xmpp = SendMsgBot(from_id, to_id, unicode(message))
xmpp.credentials['apikey'] = api_key
xmpp.credentials['accesstoken'] = o_auth_token
if xmpp.connect(('chat.facebook.com', 5222)):
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect")
However, when I run the script I get this error message:
Traceback (most recent call last):
File "sendMessagesScript.py", line 33, in <module>
xmpp = SendMsgBot(from_id, to_id, unicode(message))
File "/Library/Python/2.7/site-packages/sleekxmpp/clientxmpp.py", line 112, in __init__
self.register_plugin('feature_starttls')
File "/Library/Python/2.7/site-packages/sleekxmpp/basexmpp.py", line 264, in register_plugin
pconfig = self.plugin_config.get(plugin, {})
AttributeError: 'unicode' object has no attribute 'get'
Any ideas would be appreciated!
In the class SendMsgBot(sleekxmpp.ClientXMPP):, you need to change
def init(self, jid, recipient, message) to def __init__(self, jid, recipient, message)
I hope it will work.
Additionally, it seems that some important dashes have been ommitted from the original code.
I also had to change
xmpp.credentials['apikey'] = api_key
xmpp.credentials['accesstoken'] = o_auth_token
to
xmpp.credentials['api_key'] = api_key
xmpp.credentials['access_token'] = o_auth_token
These are apparently the parameter names that Facebook expects, as you can see in Facebook's PHP example