I would like to send an image by email with FlaskMailMessage. But this image is a base64 encoded image.
Here is an example code :
def mail_answer():
msg = "iVBORw0KGgoAAAANSUhEUgAAACkAAAAyCAYAAADBcfKuAAABP2lDQ1BJQ0MgUHJvZmlsZQAAKJFjYGDiSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8bAwcDJwMMgwSCfmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsisOVoyrvvXfnVZU7hvNU+t0TNM9SiAKyW1OBlI/wHi+OSCohIGBsYYIFu5vKQAxG4AskWKgI4CsqeA2OkQ9goQOwnC3gNWExLkDGRfALIFkjMSU4DsB0C2ThKSeDoSG2ovCLD6GpkHEnAnyaAktaIERDvnF1QWZaZnlCg4AkMnVcEzL1lPR8HIwMiIgQEU1hDVnwPBYcgodgYhlr+IgcHiKwMD8wSEWNJMBobtrQwMErcQYioLGBj4WxgYtp0vSCxKhDuA8RtLcZqxEYTN4wT05r3//z+rMTCwT2Zg+Dvh///fi/7//7sYaP4dBoYDeQANBV6yWIqalwAAAFZlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA5KGAAcAAAASAAAARKACAAQAAAABAAAAKaADAAQAAAABAAAAMgAAAABBU0NJSQAAAFNjcmVlbnNob3QNr/WAAAAB1GlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvbj41MDwvZXhpZjpQaXhlbFlEaW1lbnNpb24+CiAg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="image01.png",
name="image01.png",
content_type="image/png",
)
]
headers = {"Reply-To": "hello#test.com"}
FlaskMailMessage(
"SO test",
sender="achichi#stackoverflow.com",
recipients=["test#†est.com"],
extra_headers=headers,
attachments=attachments,
)
When I try to execute it I have the following error :
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
self.run()
File "/Users/antoine/Documents/Git/portail/portail/tools/threading.py", line 33, in run
super().run()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "/Users/antoine/Documents/Git/portail/portail/modules/notification/notifications.py", line 83, in _background_notification_handle
manager.mail_users(emailed_users, signal.name, obj)
File "/Users/antoine/Documents/Git/portail/portail/modules/helpdesk/notifications.py", line 360, in mail_users
self.mail_answer(users, ticket)
File "/Users/antoine/Documents/Git/portail/portail/modules/helpdesk/notifications.py", line 465, in mail_answer
mails.send_email(
File "/Users/antoine/Documents/Git/portail/portail/modules/mail/lib.py", line 297, in send_email
return mail.send(msg)
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/flask_mail.py", line 492, in send
message.send(connection)
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/flask_mail.py", line 427, in send
connection.send(self)
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/flask_mail.py", line 190, in send
message.as_bytes() if PY3 else message.as_string(),
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/flask_mail.py", line 385, in as_bytes
return self._message().as_bytes()
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/flask_mail.py", line 350, in _message
f.set_payload(attachment.data)
File "/Users/antoine/Documents/Git/portail/venv/lib/python3.10/site-packages/werkzeug/datastructures.py", line 3023, in __getattr__
return getattr(self.stream, name)
AttributeError: '_io.BytesIO' object has no attribute 'data'
FlaskMail attachments are a list[FileStorage], maybe I do not need io.BytesIO(msg) ? But what should I use instead ?
Judging from the Documentation, it's not a FileStorage that's expected,
as the arguments parameter, but rather an Attachment object (can be seen from the source code as well).
So the actual code to attach a file to the message would be :
def mail_answer():
msg = "iVBORw0KGgoAAAANSUhEUgAAACkAAAAyCAYAAADBcfKuAAABP2lDQ1BJQ0MgUHJvZmlsZQAAKJFjYGDiSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8bAwcDJwMMgwSCfmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsisOVoyrvvXfnVZU7hvNU+t0TNM9SiAKyW1OBlI/wHi+OSCohIGBsYYIFu5vKQAxG4AskWKgI4CsqeA2OkQ9goQOwnC3gNWExLkDGRfALIFkjMSU4DsB0C2ThKSeDoSG2ovCLD6GpkHEnAnyaAktaIERDvnF1QWZaZnlCg4AkMnVcEzL1lPR8HIwMiIgQEU1hDVnwPBYcgodgYhlr+IgcHiKwMD8wSEWNJMBobtrQwMErcQYioLGBj4WxgYtp0vSCxKhDuA8RtLcZqxEYTN4wT05r3//z+rMTCwT2Zg+Dvh///fi/7//7sYaP4dBoYDeQANBV6yWIqalwAAAFZlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA5KGAAcAAAASAAAARKACAAQAAAABAAAAKaADAAQAAAABAAAAMgAAAABBU0NJSQAAAFNjcmVlbnNob3QNr/WAAAAB1GlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWURpbWVuc2lvb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.b64encode(msg)
headers = {"Reply-To": "hello#test.com"}
msg = FlaskMailMessage(
"SO test",
sender="achichi#stackoverflow.com",
recipients=["test#†est.com"],
extra_headers=headers
)
msg.attach("filename.png", "image/png", data_bytes)
# ...
Related
I'm new to python, and I am trying to build a little Reddit bot to get some practice.
My bot works just fine (tested many times) but once I try to move the credentials to a .env file it fails.
I've ran pip3 install python-dotenv
This is my code, just one file, removing irrelevant stuff:
import os
import praw
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from dotenv import load_dotenv
load_dotenv()
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://makideat-6a-default-db.firebaseio.com'
})
db_ref = db.reference()
reddit = praw.Reddit(
client_id=os.getenv('CLIENT_ID'),
client_secret=os.getenv('CLIENT_SECRET'),
username=os.getenv('USERNAME'),
password=os.getenv('PASSWORD'),
user_agent=os.getenv('USER_AGENT')
)
def summoned_reply(comment):
DO SOME STUFF...
messages = reddit.inbox.stream() # creates an iterable for your inbox and streams it
for message in messages: # iterates through your messages
try:
if message in reddit.inbox.mentions() and message in reddit.inbox.unread():
summoned_reply(message)
message.mark_read()
except praw.exceptions.APIException:
print("probably a rate limit....")
And this is the error I'm getting (line 56 is for message in messages:):
Traceback (most recent call last):
File "C:\Users\Yanay\Documents\Coding\NiceAndPretty\main.py", line 56, in <module>
for message in messages: # iterates through your messages
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\util.py", line 195, in stream_generator
for item in reversed(list(function(limit=limit, **function_kwargs))):
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 63, in __next__
self._next_batch()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 89, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 634, in get
return self._objectify_request(method="GET", params=params, path=path)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 739, in _objectify_request
self.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 941, in request
return self._core.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 330, in request
return self._request_with_retries(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 425, in refresh
self._request_token(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
Then, in the same directory I have a .env file in the following structure (changed characters for everything here of course, but haven't changed the structure or added or removed spaces from anywhere):
CLIENT_ID=gGATUW-Ea507LoQ
CLIENT_SECRET=_b6vCCHKBCqVHzlJin3sEQ
USERNAME=Maddeeat
PASSWORD=!Neatat!
USER_AGENT=Maddeeat:1.0.0 (by u/Maddeeat)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(NODE, username=SETTINGS['username'], password=SETTINGS['password'])
Could someone tell me what this error means when I try to ssh with paramiko?
Traceback (most recent call last):\r\n
File "/path/stats.py", line 104, in connect\r\n
ssh.connect(NODE, username=SETTINGS['username'], password=SETTINGS['password'])\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/client.py", line 367, in connect\r\n
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/client.py", line 558, in _auth\r\n
key = pkey_class.from_private_key_file(filename, password)\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/pkey.py", line 184, in from_private_key_file\r\n
key = cls(filename=filename, password=password)\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/ecdsakey.py", line 49, in __init__\r\n
self._from_private_key_file(filename, password)\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/ecdsakey.py", line 146, in _from_private_key_file\r\n
self._decode_key(data)\r\n
File "/usr/software/lib/python3.2/site-packages/paramiko-1.16.0-py3.2.egg/paramiko/ecdsakey.py", line 161, in _decode_key\r\n
key = SigningKey.from_der(data)\r\n
File "/usr/software/lib/python3.2/site-packages/ecdsa-0.13-py3.2.egg/ecdsa/keys.py", line 178, in from_der\r\n
curve_oid, empty = der.remove_object(curve_oid_str)\r\n
File "/usr/software/lib/python3.2/site-packages/ecdsa-0.13-py3.2.egg/ecdsa/der.py", line 82, in remove_object\r\n
raise UnexpectedDER("wanted object (0x06), got 0x%02x" % n)\r\n
ecdsa.der.UnexpectedDER: wanted object (0x06), got 0x30\r\n
While I'm not sure why this was happening, I was able to work around it by passing look_for_keys=False to connect().
Hello everyone im trying to subscribe to the Instagram API, but for some reason i keep on getting an error.
code:
# Subscribe to all media in a geographic area
api.create_subscription(object='geography', lat=35.657872, lng=139.70232, radius=1000, aspect='media', callback_url='http://locallhost.com/')
Error:
Traceback (most recent call last):
File "C:/Users/Owner.Owner-PC/Documents/Final Year Project/testing.py", line 26, in <module>
api.create_subscription(object='geography', lat=35.657872, lng=139.70232, radius=1000, aspect='media', callback_url='http://locallhost.com/')
File "C:\Python 3.5\lib\site-packages\instagram\bind.py", line 197, in _call
return method.execute()
File "C:\Python 3.5\lib\site-packages\instagram\bind.py", line 189, in execute
content, next = self._do_api_request(url, method, body, headers)
File "C:\Python 3.5\lib\site-packages\instagram\bind.py", line 123, in _do_api_request
signature = hmac.new(secret, ips, sha256).hexdigest()
File "C:\Python 3.5\lib\hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "C:\Python 3.5\lib\hmac.py", line 42, in __init__
raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'
Now i am very confused what the error is, can someone please explain how to solve this?
So initially I connect to a server with:
soapclient = Client(url, transport=WindowsHttpAuthenticated(username=user, password=passwd))
and this works fine because when I print it it shows all of its properties correctly.
Then I run:
request = self.soapclient.factory.create('ns3:CRRequest')
request['ChangeRequestId'] = '601904'
response = self.soapclient.service.GetChangeRequestById([request])
And then I get an error on the response line which reads:
Traceback (most recent call last):
File "C:\Users\nlujan\Desktop\prism_source.py", line 63, in <module>
CR = prism.getChangeRequestById('601904')
File "C:\Users\nlujan\Desktop\prism_source.py", line 36, in getChangeRequestById
response = self.soapclient.service.GetChangeRequestById([request])
File "build\bdist.win32\egg\suds\client.py", line 542, in __call__
return client.invoke(args, kwargs)
File "build\bdist.win32\egg\suds\client.py", line 602, in invoke
File "build\bdist.win32\egg\suds\client.py", line 643, in send
result = self.succeeded(binding, reply.message)
File "build\bdist.win32\egg\suds\client.py", line 678, in succeeded
reply, result = binding.get_reply(self.method, reply)
File "build\bdist.win32\egg\suds\bindings\binding.py", line 149, in get_reply
soapenv.promotePrefixes()
AttributeError: 'NoneType' object has no attribute 'promotePrefixes'
I had someone else run my script and it works fine on their computer but I keep getting an error in mine. I've installed several different versions of python to see if that's the problem but with no luck. Does anyone see what could be the problem?
Try to add an endpoint address
client = Client('url', location = "https://someurl/services")
Hey, any idea about what is the timeout error which I am getting here:
Error trace:
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "sync_server.py", line 853, in put_file
return RequestController_v1_0.put_file(self, *args, **kw)
File "sync_server.py", line 409, in put_file
saved_path, tgt_path, root_folder = self._save_file(client_id, theFile)
File "sync_server.py", line 404, in _save_file
saved_path, tgt_path, root_folder = get_posted_file(cherrypy.request, 'theFile', staging_path)
File "sync_server.py", line 1031, in get_posted_file
, keep_blank_values=True)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 496, in __init__
self.read_multi(environ, keep_blank_values, strict_parsing)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 620, in read_multi
environ, keep_blank_values, strict_parsing)
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 498, in __init__
self.read_single()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 635, in read_single
self.read_lines()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 657, in read_lines
self.read_lines_to_outerboundary()
File "/array/purato/python2.6/lib/python2.6/cgi.py", line 685, in read_lines_to_outerboundary
line = self.fp.readline(1<<16)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 206, in readline
data = self.rfile.readline(size)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 868, in readline
data = self.recv(self._rbufsize)
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/wsgiserver/__init__.py", line 747, in recv
return self._sock.recv(size)
timeout: timed out
Here is the code which is getting called:
def get_posted_file(request, form_field_name, tgt_folder, tgt_fname=None):
logger.debug('get_posted_file: %s' % request.headers['Last-Modified'])
lowerHeaderMap = {}
for key, value in request.headers.items():
lowerHeaderMap[key.lower()] = value
---> dataDict = TmpFieldStorage(fp=request.rfile, headers=lowerHeaderMap, environ={'REQUEST_METHOD':'POST'}
, keep_blank_values=True)
and:
class TmpFieldStorage(cgi.FieldStorage):
"""
Use a named temporary file to allow creation of hard link to final destination
"""
def make_file(self, binary=None):
tmp_folder = os.path.join(get_filer_root(cherrypy.request.login), 'sync_tmp')
if not os.path.exists(tmp_folder):
os.makedirs(tmp_folder)
return tempfile.NamedTemporaryFile(dir=tmp_folder)
environ={'REQUEST_METHOD':'POST'}
That seems a rather deficient environ. The CGI spec requires many more environment variables to be in there, some of which the cgi module is going to need.
In particular there is no CONTENT_LENGTH header. Without it, cgi is defaulting to reading the entire contents of the stream up until EOF. But since it is (probably) a network stream rather than a file there will be no EOF (or at least not one directly at the end of the submission), so the form reader will be sitting there waiting for more input that will never come. Timeout.