Send transactional and marketing emails using 'SendInBlue' - python

I want to send transactional and marketing emails using 'SendInBlue'. I also want to use Python language to do the same. I have visited the API doc of SendInBlue and followed the same procedure, still unsuccessful in sending the emails.
from mailin import Mailin
m = Mailin("https://api.sendinblue.com/v2.0","ScrWGqd296ya0CWq")
data = { "to" : {"aman#gmail.com":"to whom!"},
"from" : ["amandeep#gmail.com", "from email!"],
"subject" : "Subject...",
"html" : "This is the <h1>HTML</h1>",
"attachment" : ["https://example.com/path-to-file/filename1.pdf", "https://example.com/path-to-file/filename2.jpg"]
}
result = m.send_email(data)
print(result)
I have also downloaded mailin-api-python from github and ran this script. I don't have any idea where to setup to my smtp details.
**I have changed the API key just for security purpose.

I would strongly recommend you to use the latest version of SendinBlue's Python wrapper where they have provided an example
from __future__ import print_function
import time
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
# Configure API key authorization: api-key
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'API-KEY'
# create an instance of the API class
api_instance = sib_api_v3_sdk.SMTPApi(sib_api_v3_sdk.ApiClient(configuration))
senderSmtp = sib_api_v3_sdk.SendSmtpEmailSender(name="test",email="youremail#gmail.com")
sendTo = sib_api_v3_sdk.SendSmtpEmailTo(email="recipientEmail#gmail.com",name="Recipient Name")
arrTo = [sendTo] #Adding `to` in a list
send_smtp_email = sib_api_v3_sdk.SendSmtpEmail(sender=senderSmtp,to=arrTo,html_content="This is a test",subject="This is a test subject") # SendSmtpEmail | Values to send a transactional email
try:
# Send a transactional email
api_response = api_instance.send_transac_email(send_smtp_email)
pprint(api_response)
except ApiException as e:
print("Exception when calling SMTPApi->send_transac_email: %s\n" % e)
I got a sample script working:
I successfully received the email and the messageId as the response.
Please let me know if it helps!

Related

"Key not found" after fixing Python error: AttributeError: module 'sib_api_v3_sdk.configuration' has no attribute 'api_key' at Sendinblue.com

I am trying to send e-mail campaign mails with the SMTP API of Sendinblue.com, a cloud-based marketing communication software suite. I am running my configuration of the template script provided by Sendinblue as seen on the screenshot:
My initial script was as follows:
# ------------------
# Create a campaign\
# ------------------
# Include the Sendinblue library\
from __future__ import print_function
import time
from datetime import datetime
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
myapikey = 'xkeysib-.................................' # full api key
# Instantiate the client\
sib_api_v3_sdk.configuration.api_key['api-sb'] = myapikey
api_instance = sib_api_v3_sdk.EmailCampaignsApi()
# Define the campaign settings\
email_campaigns = sib_api_v3_sdk.CreateEmailCampaign(
name= "Campaign sent via the API",
subject= "My subject",
sender= { "name": "From name", "email": "------#gmail.com"}, # personal email with which I was registered # sendinblue
type= "classic",
# Content that will be sent\
html_content= "Congratulations! You successfully sent this example campaign via the Sendinblue API.",
# Select the recipients\
recipients= {"listIds": [2, 7]},
# Schedule the sending in one hour\
scheduled_at = datetime.now()
)
# Make the call to the client\
try:
api_response = api_instance.create_email_campaign(email_campaigns)
pprint(api_response)
except ApiException as e:
print("Exception when calling EmailCampaignsApi->create_email_campaign: %s\n" % e)
I referred to Sendinblue Documentation in the cases where I had doubt. Most of the process seems self-explanatory, just the line with configuration.api_key['api-key'] = 'YOUR API KEY' was ambiguous as it is not quite clearly stated how exactly the api-key should be passed and the attribute of api_key I assumed api_key was holding the name of the API as defined in the SMTP & API Advanced tab. Even if I assume it should be holding some other values, it is not clear what they should be, what I can tell for sure is that sib_api_v3_sdk.configuration.api_key['api-key'] also resulted in AttributeError: module 'sib_api_v3_sdk.configuration' has no attribute 'api_key'.
After initially getting the error AttributeError: module 'sib_api_v3_sdk.configuration' has no attribute 'api_key' I researched a dozen of articles on StackOverflow, one of them on the Kubernetes topic where the script seemed to throw a similar error like the one I was getting, so I followed the advices described in Python kubernetes module has no attribute 'api_key'. Therefore, I tried reassigning the class attributes as follows:
configuration.api_key['api-sb'] = myapikey
api_instance = sib_api_v3_sdk.EmailCampaignsApi()
The fact that now I wasn't getting the error of a missing key but facing an 'unauthorized' message cheered me up for a short time, until I spent several hours trying to get past this. So the script that's now throwing the HTTP response body: {"message":"Key not found","code":"unauthorized"} is now this:
# ------------------
# Create a campaign\
# ------------------
# Include the Sendinblue library\
from __future__ import print_function
import time
from datetime import datetime
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
from pprint import pprint
myapikey = 'xkeysib-c..............' # key
# Instantiate the client\
sib_api_v3_sdk.configuration.api_key['api-sb'] = myapikey
api_instance = sib_api_v3_sdk.EmailCampaignsApi()
# Define the campaign settings\
email_campaigns = sib_api_v3_sdk.CreateEmailCampaign(
name= "Campaign sent via the API",
subject= "My subject",
sender= { "name": "From name", "email": "mail....#gmail.com"}, # personal gmail with which I was initially registered # sendinblue.com
type= "classic",
# Content that will be sent\
html_content= "Congratulations! You successfully sent this example campaign via the Sendinblue API.",
# Select the recipients\
recipients= {"listIds": [2, 7]},
# Schedule the sending in one hour\
scheduled_at = datetime.now()
)
# Make the call to the client\
try:
api_response = api_instance.create_email_campaign(email_campaigns)
pprint(api_response)
except ApiException as e:
print("Exception when calling EmailCampaignsApi->create_email_campaign: %s\n" % e)
My 1st question is: was my 1st script wrong and in what way?
Secondly: Is configuration.api_key['api-sb'] = myapikey the correct syntax, assuming that 'api-sb' is the name of my API key as shown on the screenshot?
And third: In the myapikey variable, when assigning the API key itself, should there be anything else as a prefix to the key?
Try this sample transactional email script. Worked for me in python.
https://developers.sendinblue.com/reference/sendtransacemail
Instead of this:
sib_api_v3_sdk.configuration.api_key['api-sb'] = myapikey
api_instance = sib_api_v3_sdk.EmailCampaignsApi()
do this:
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-sb'] = myapikey
api_instance = sib_api_v3_sdk.EmailCampaignsApi(sib_api_v3_sdk.ApiClient(configuration))
as shown in https://developers.sendinblue.com/reference/createemailcampaign-1.

Dialogflow API access follow up intent in Python

I am following the following tutorial to understand Dialogflow Python API.
Here is how my adaptation looks:
import dialogflow_v2 as dialogflow
import json
from google.api_core.exceptions import InvalidArgument
from google.oauth2 import service_account
dialogflow_key = json.load(open(r'path_to_json_file.json'))
credentials = (service_account.Credentials.from_service_account_info(dialogflow_key))
session_client = dialogflow.SessionsClient(credentials=credentials)
DIALOGFLOW_LANGUAGE_CODE = 'en-US'
DIALOGFLOW_PROJECT_ID = 'some_project_id'
SESSION_ID = 'current-user-id'
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_to_be_analyzed = "mobile data"
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except InvalidArgument:
raise
print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)
Here is what program outputs:
Query text: mobile data
Detected intent: support.problem
Detected intent confidence: 0.41999998688697815
Fulfillment text: Make sure mobile data is enabled and Wi-Fi is turned off.
Now my intent support.problem has follow up intent support.problem-yes, where customer replies Done it and gets back another response Let us try another step
How do I pass text/query to follow up intent and how do I get response in Python?
The response.query_result object should also contain an output_context field, which should be an array of Context objects. This array should be passed in query_parameters.context you pass to detect_intent().
You should be able to create a dictionary with the query parameters fields (including one for context) that you pass to session_client.detect_intent.

suds.WebFault: Server raised fault: 'org.xml.sax.SAXException: Invalid type: employees'

I am new to netsuite and I have to integrate the netsuite my current application. I have written the following code to login into the netsuite sandbox environment and create a new data entry into the database.
from suds.client import Client
import os, time, sys, datetime
import suds
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
reload(sys)
sys.setdefaultencoding('utf8')
NS_HOST = 'https://webservices.sandbox.netsuite.com'
email ='utkarsh.sharma#ABCD.com'
pwd ='ABCDEFGHI!'
account = "3828138"
NS_ENDPOINT = "2017_1"
NS_ROLE = 25
wsdl = 'https://webservices.sandbox.netsuite.com/wsdl/v2017_1_0/netsuite.wsdl'
client = Client(url=wsdl)
ApplicationInfo = client.factory.create('ns16:ApplicationInfo')
ApplicationInfo.applicationId = "A8C51D62-63FC-42DC-AE13-B1B971F41C47"
client.set_options(location= NS_HOST + "/services/NetSuitePort_" +
NS_ENDPOINT, soapheaders={'applicationInfo':ApplicationInfo})
passport = client.factory.create('ns4:Passport')
passport.email = email
passport.password = pwd
passport.account = account
loginResponse = client.service.login(passport,_soapheaders=
{'applicationInfo': ApplicationInfo})
print('Login Response: ')
print (loginResponse.status)
recordRef = client.factory.create('ns4:RecordRef')
recordRef._internalId = 123456789
recordRef._type = 'employees'
record = client.service.get(recordRef)
print (record)
I can login but while trying to post the data, I am facing the following error.
suds.WebFault: Server raised fault: 'org.xml.sax.SAXException: Invalid type: employees'
Any kind of help is welcomed. Thanks in advance.
The record type should be singular. Try setting recordRef.type = 'employee', not 'employees'. Record types will usually be the singular version like, invoice, salesorder, customer, vendor.

how to use designed template in django using sendgrid API?

I have integrate the send-grid with my Django application and mails also sent successfully. But now I want to send email with designed template from my django application. I have read the docs also, but not get any idea how to use it programatically. This is my first time to use send-grid. Please can anyone help me to find out the way how can I send send-grid template from django application.
You can use SendGrid's Template Engine to store a template inside SendGrid. You then reference that template ID when sending an email via the SendGrid API, you can see an example of that code in the sendgrid-python library.
Here it is in a full example, it uses a SendGrid API key (you can find out how to get that set up by reading this guide):
import sendgrid
sg = sendgrid.SendGridClient('sendgrid_apikey')
message = sendgrid.Mail()
message.add_to('John Doe <john#email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe#email.com>')
# This next section is all to do with Template Engine
# You pass substitutions to your template like this
message.add_substitution('-thing_to_sub-', 'Hello! I am in a template!')
# Turn on the template option
message.add_filter('templates', 'enable', '1')
# Tell SendGrid which template to use
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')
# Get back a response and status
status, msg = sg.send(message)
You need Sendgrid-Python interface first:
pip install sendgrid
after that try this:
import os
from sendgrid.helpers.mail import Mail
from sendgrid import SendGridAPIClient
FROM_EMAIL = 'Your_Name#SendGridTest.com'
# update to your dynamic template id from the UI
TEMPLATE_ID = 'd-d027f2806c894df38c59a9dec5460594'
# list of emails and preheader names, update with yours
TO_EMAILS = [('your_email#domain.com', 'Sourabh MbeforL'),]
def SendDynamic():
message = Mail(
from_email=FROM_EMAIL,
to_emails=TO_EMAILS)
# pass custom values for our HTML placeholders
message.dynamic_template_data = {
'subject': 'SendGrid Development',
'place': 'New York City',
'event': 'Twilio Signal'
}
message.template_id = TEMPLATE_ID
try:
sg = SendGridAPIClient(os.environ.get('YOUR_SENDGRID_API_KEY')) ## (^_^) This face is just to grab your attention for api key needed
response = sg.send(message)
code, body, headers = response.status_code, response.body, response.headers
print(f"Response code: {code}")
print(f"Response headers: {headers}")
print(f"Response body: {body}")
print("Dynamic Messages Sent!")
except Exception as e:
print("Error: {0}".format(e))
return str(response.status_code)

Facebook Posting to a Page

I am trying to post to the wall of a facebook page that I am administrator (not profile), however no luck. How do I achieve this ? I'm stucked at the page access token retrieval part.
#!/usr/bin/python
# coding: utf-8
import facebook
import urllib
import urlparse
import subprocess
import warnings
# Hide deprecation warnings. The facebook module isn't that up-to-date (facebook.GraphAPIError).
warnings.filterwarnings('ignore', category=DeprecationWarning)
# Parameters of your app and the id of the profile you want to mess with.
FACEBOOK_APP_ID = 'XXXXXXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXX'
FACEBOOK_PROFILE_ID = 'XXXXXXXXXXX'
# Trying to get an access token. Very awkward.
oauth_args = dict(client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_APP_SECRET,
scope = 'manage_pages',
response_type = 'token'
)
oauth_curl_cmd = ['curl',
'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)]
oauth_response = subprocess.Popen(oauth_curl_cmd,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE).communicate()[0]
print urllib.urlencode(oauth_args)
try:
oauth_access_token = urlparse.parse_qs(str(oauth_response))['access_token'][0]
except KeyError:
print('Unable to grab an access token!')
exit()
print oauth_access_token
facebook_graph = facebook.GraphAPI(oauth_access_token)
# Try to post something on the wall.
try:
fb_response = facebook_graph.put_wall_post('Hello from Python', \
profile_id = FACEBOOK_PROFILE_ID)
print fb_response
except facebook.GraphAPIError as e:
print 'Something went wrong:', e.type, e.message
I would not recommend doing this through the command line with curl as it is less secure and less reliable. You can do all of this with the urllib2 and json modules
to get the access token you just want to make a call to https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
so you would do:
url='https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials'
target=urllib2.urlopen(url)
token = target.read()[13:]
EDIT:
My bad, I forgot that facebook/oauth gives you the access token in plain text so you don't need the json module. I've updated the example to show what you should be doing. Note target.read() will give you the string 'access_token=ACCESS_TOKEN' and then you are just parsing it to remove the identifier.
to see what response is go to the url and put in your information you will a json dict with acess_token.
the second half of this page should have all the information you need.

Categories