Python - Sending email with attachment using GMAIL smtp gives error - python-2.7

I'm trying to send an email using Python and Google's smtp. After calling it I get an error:
msg = MIMEMultipart('alternative')
TypeError: 'LazyImporter' object is not callable
Did anyone had the same problem ? What's the solution for that ?
My code:
Pastebin code

Just change your imports to
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase

Related

Invoking an endpoint in AWS with a multidimensional array

I have deployed a Tensorflow-Model in SageMaker Studio following this tutorial:
https://aws.amazon.com/de/blogs/machine-learning/deploy-trained-keras-or-tensorflow-models-using-amazon-sagemaker/
The Model needs a Multidimensional Array as input. Invoking it from the Notebook itself is working:
import numpy as np
import json
data = np.load("testValues.npy")
pred=predictor.predict(data)
But I wasnt able to invoke it from a boto 3 client using this code:
import json
import boto3
import numpy as np
import io
client = boto3.client('runtime.sagemaker')
datain = np.load("testValues.npy")
data=datain.tolist();
response = client.invoke_endpoint(EndpointName=endpoint_name, Body=json.dumps(data))
response_body = response['Body']
print(response_body.read())
This throws the Error:
An error occurred (ModelError) when calling the InvokeEndpoint operation: Received client error (415) from model with message "{"error": "Unsupported Media Type: Unknown"}".
I guess the reason is the json Media Type but i have no clue how to get it back in shape.
I tried this:https://github.com/aws/amazon-sagemaker-examples/issues/644 but it doesnt seem to change anything
This fixed it for me:
The Content Type was missing.
import json
import boto3
import numpy as np
import io
client = boto3.client('runtime.sagemaker',aws_access_key_id=..., aws_secret_access_key=...,region_name=...)
endpoint_name = '...'
data = np.load("testValues.npy")
payload = json.dumps(data.tolist())
response = client.invoke_endpoint(EndpointName=endpoint_name,
ContentType='application/json',
Body=payload)
result = json.loads(response['Body'].read().decode())
res = result['predictions']
print("test")

My webservice with oauth2client don't work on remote server,

The django app runs on the local server, but does not work on the remote.
The server does not have a GUI and does not provide the user with a link to authorization. The server outputs link to the console.
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import os
import json
SCOPES = 'https://www.googleapis.com/auth/calendar'
from .models import Aim
try:
import argparse
flags = tools.argparser.parse_args([])
except ImportError:
flags = None
def calendar_authorization(username):
store = open('app/static/secret_data/' + username +'.json', 'w')
store.close()
store = file.Storage('app/static/secret_data/' + username +'.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('app/client_secret.json', SCOPES)
flags.noauth_local_webserver = True
print("________flow_______")
print(flow.__dict__)
creds = tools.run_flow(flow, store, flags)
print("________creds_______")
print(creds.__dict__)
In the local version, I use client_secret.json, obtained from OAuth 2.0 client IDs. I suspect that I may have the wrong settings for this.
I found the information to use the Service account keys(I don't use it now). But I didn’t find a good setup guide for this.
How to set it up and paste in the code for authorization(
I did not understand how the access service key is used in the code?)?
What could be wrong?

Sending Emails on GAE through smtp.gmail.com in Python

After reading Google's documentation it should be possible to send an email via smtp.gmail.com on port 465 or 587 on GAE standard.
Reference: https://cloud.google.com/appengine/docs/standard/python/sockets/#limitations_and_restrictions_if_lang_is_java_java_7_runtime_only_endif
What is not documented is how to use the socket library.
I am able to send an email via smtplib running the python script locally.
server = smtplib.SMTP_SSL("smtp.gmail.com", 587)
server.ehlo()
server.login(gmail_access["email"], gmail_access["password"])
server.sendmail(gmail_access["email"], report.owner, msg.as_string())
server.close()
When trying to run the code with GAE's dev_appserver I get the nondescript error "[Errno 13] Permission denied"
Any assistance would be greatly appreciated.
Oddly enough the error only occurs when trying to run the code locally with dev_appserver.py. After deploying the code to App Engine it worked.
import socket
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = gmail_access["email"]
msg["To"] = report.owner
msg.attach(MIMEText(body, "html"))
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.ehlo()
server.login(gmail_access["email"], gmail_access["password"])
server.sendmail(gmail_access["email"], report.owner, msg.as_string())
server.close()

AWS Lambda - Generate CSV In Memory and send it as an attachment to an Email

I'm trying to write an AWS Lambda service using Python 2.7 that will generate an In-Memory CSV file and email it as an attachment. I feel like I'm close with this script based on what I've learned but I'm not quite there.
# Import smtplib for the actual sending function
import smtplib
import sys
import csv
import cStringIO
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# Import the email modules we'll need
server = smtplib.SMTP('smtp.postmarkapp.com', 587)
server.starttls()
server.login('.....','.....')
list = []
row1 = ["One","Two","Three"]
list.append(row1)
msg = MIMEMultipart()
msg['To'] = "daniel#mydomain.com"
msg['From'] = "noreply#mydomain.com"
msg['Subject'] = "DG Test subject"
msg.attach(MIMEText("Test Message"))
csv_buffer = cStringIO.StringIO()
writer = csv.writer(csv_buffer, lineterminator='\n')
writer.writerow(["1","2","3"])
for row in list:
writer.writerow(row)
print(csv_buffer.getvalue())
msg.attach(csv_buffer)
try:
response = server.sendmail(msg['From'], ["daniel#mydomain.com"],msg.as_string())
server.quit()
except AttributeError as error:
print(error)
else:
print(response)
This gives me the following error:
1,2,3
One,Two,Three
'cStringIO.StringO' object has no attribute 'get_content_maintype'
Basically it comes down to not being sure how to use the csv_buffer object. Assuming I just need to add that attribute to the object somehow but I'm not quite sure how. If I try to add any additional arguments to the .attach() line, it complains that I have too many arguments.
Thanks!
I figured it out, thanks to stitching together a few SO posts.
import cStringIO
import csv
csv_buffer = cStringIO.StringIO()
writer = csv.writer(csv_buffer, delimiter=',', quoting=csv.QUOTE_ALL)
writer.writerow(["1","2","3"])
for row in list:
writer.writerow(row)
print(csv_buffer.getvalue())
# new lines
csv_file = MIMEText(csv_buffer.getvalue())
attachment = csv_file.add_header('Content-Disposition', 'attachment', filename="csv_file.csv")
msg.attach(csv_file)

Invalid syntax error in google python api

I am new to google python api client.I am learning from https://developers.google.com/api-client-library/python/start/get_started.I want to make an api which converts python object into JSON data and sends to a servlet.
The python code of file api.py:
import os
import urllib2
import httplib2
import json
import requests
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run_flow
from oauth2client.file import Storage
from oauth2client import tools
api_version='1'
_file_="D:\API"
CLIENT_SECRETS = os.path.join(os.path.dirname(_file_))
flow=flow_from_clientsecrets(CLIENT_SECRETS,
scope=[
'https://www.googleapis.com/auth/devstorage.full_control',
],
http = httplib2.Http()
auth_http = credentials.authorize(http)
service=build('SendNotif',api_version,http=http)
req = urllib2.Request('http://example/notify')
req.add_header('Content-Type', 'application/json')
data={"message":"Hello User you are notified"}
data_json = json.dumps(data)
response = urllib2.urlopen(req, json.dumps(data))
The error shown is:
D:\API>python api.py
File "api.py", line 25
auth_http = credentials.authorize(http)
^
SyntaxError: invalid syntax
please do help in correcting me..
thanks in advance....
You're missing a closing parenthesis for this line:
flow=flow_from_clientsecrets(CLIENT_SECRETS,