I have errors when I use reply_to, here is what I've tried...
This works but without reply_to :
mail = Mail(
from_email = from_email,
to_emails = to_email,
subject = subject,
html_content = content)
response = sg.client.mail.send.post(request_body=mail.get())
And I've tried this :
mail = Mail(
reply_to = reply,
from_email = from_email,
to_emails = to_email,
subject = subject,
html_content = content)
response = sg.client.mail.send.post(request_body=mail.get())
This thows :
TypeError: init() got an unexpected keyword argument 'reply_to'
I have also tried to add this after Mail() :
mail.from_EmailMessage(reply_to=ReplyTo(Email(email=ANS_EMAIL,name='Mr X')))
Which throws :
TypeError: object of type 'Email' has no len()
And :
mail.reply_to(ReplyTo(email=ANS_EMAIL,name='Mr X'))
Which throws :
TypeError: 'NoneType' object is not callable
Any help please ?
As your error states reply_to is not accepted in init(). Try setting reply_to after you have created the Mail object.
Example Below:
mail.reply_to = "reply-to#website.com"
or
message.reply_to = ReplyTo('reply-to#website.com', 'Reply Here')
More details on how to customize sendgrid email object - Link
I managed doing this :
data = {
"personalizations": [
{
"send_at": date,
"subject": objet,
"to": [{"email": to_email}],
}
],
"from": {"email": FROM_EMAIL, "name": "..."},
"reply_to": {"email": "...#...", "name": "..."},
"send_at": date,
"subject": objet,
"content": [
{
"type": "text/html",
"value": body
}
]
}
response = sg.client.mail.send.post(request_body=data)
Related
I am trying to use the POST method of Amadeus flight availabilities API on Python, but is is still giving me error 400. Any suggestions? Many thanks.
from amadeus import Client, ResponseError, Location
import requests
amadeus = Client(
client_id='My ID',
client_secret='My Secret')
try:
flights = amadeus.get('/v2/shopping/flight-offers',originLocationCode = "GIG",destinationLocationCode = "ATL",departureDate = "2023-01-31",nonStop = "true",travelClass = "BUSINESS",adults = 1)
body = flights.data[0]
print(body)
except ResponseError as error:
print(error)
try:
availability = amadeus.post('/v1/shopping/availability/flight-availabilities', body)
print(availability.result)
except ResponseError as error:
print('headers: ', error.response.request.headers)
print('body: ', error.response.request.params)
As per their API documentation, the body of the second API call needs to be in the following format:
{
"originDestinations": [
{
"id": "1",
"originLocationCode": "BOS",
"destinationLocationCode": "MAD",
"departureDateTime": {
"date": "2021-11-14",
"time": "21:15:00"
}
}
],
"travelers": [
{
"id": "1",
"travelerType": "ADULT"
}
],
"sources": [
"GDS"
]
}
Right now you are just feeding the second call the return from the first, which doesn't seem to be what they're looking for.
You might also need to feed the proper headers, something like:
headers = {"Content-Type": "application/json; charset=utf-8"}
then you would do
response = requests.post(url, headers=headers, json=body)
I'm trying to unit test my code and make sure the my code returns a dict that matches the class. The error says the success field required (type=value_error.missing). If when I make the bool Optional it shows my actual results with success = None, message = None etc. So my actual class is returning empty and not equal to my wb_response.
class WorkBoardCreateUserResponse(BaseModel):
success: bool
message: Optional[str]
data: Optional[CreateUserData]
error: Optional[str]
error_description: Optional[str]
#mock.patch("workboard.requests.post")
#mock.patch("workboard.requests.get")
def test_create_workboard_user(self, mock_get, mock_post):
wb_response = {
"success":True,
"message": "",
"data": {
"totalCount": 1,
"user":
{ "user_id": 1,
"user_name":"",
"wb_email":"wb#email",
"email": "abc#company",
"first_name": "F name",
"last_name": "L name",
"manager_id": "manager#company",
"profile": {
"title": "emp",
"company": "company"
}
}
}
}
wb_user = WorkBoardUserRequest(
email= "abc#capone",
first_name= "F name",
last_name= "L name",
manager_id= "manager#company",
profile=WorkBoardProfile(
title="title",
company="company"
)
)
workboard_resp = json.dumps(wb_response)
mock_post.return_value.text = token_resp
mock_post.status_code = 200
mock_get.json.return_value.text = workboard_resp
final_response = json.loads(workboard_resp)
print(type(final_response))
employee = WorkBoard("client", "secret", "env", "vendor_token")
response = employee.create_workboard_user(wb_user)
self.assertEqual(response, WorkBoardCreateUserResponse(**final_response))
def create_workboard_user(self, wbUser: WorkBoardUserRequest) -> WorkBoardResponse:
"""
Grant access to the user by invoking the Third Party API
"""
wb_url = (PROD_URL if self.environment ==
"PROD" else NON_PROD_URL) + CREATE_USER_ENDPOINT
# Invoke the WorkBoard API to create user access
try:
create_user_response = requests.post(
wb_url, data=wbUser.json(), verify=True, allow_redirects=False, headers=self.headers
)
response = json.loads(create_user_response.text)
create_user_response = WorkBoardCreateUserResponse(**response)
logger.info(f"WorkBoard create user response : (%s)", create_user_response)
except ValidationError as validation_error:
print(f"Error while reading response : ", str(validation_error))
raise RuntimeError(str(validation_error))
except Exception as err:
logger.exception(f"Error while creating workboard user : %s", str(err))
raise RuntimeError(str(err))
return create_user_response
def getbodyinbox():
service = build('gmail', 'v1', credentials=creds)
label_name = "READ-BY-SCRIPT"
label_id = 'Label_8507504117657095973'
results = service.users().messages().list(
userId='me', q="-label:"+label_name, maxResults=1).execute()
messages = results.get('messages', [])
body = []
if not messages:
body = "no messages"
return body
else:
for message in messages:
msg = service.users().messages().get(
userId='me', id=message['id']).execute()
labels = msg['labelIds']
if "INBOX" in labels:
headers = msg['payload']['headers']
headers = str(headers)
print(headers)
if "class_ix" in headers:
body.append(msg['payload']['parts'])
if 'data' in body[0][0]['body']:
body = base64.urlsafe_b64decode(
body[0][0]['body']['data'])
elif 'data' in body[0][1]['body']:
body = base64.urlsafe_b64decode(
body[0][1]['body']['data'])
body = str(body)
return body
print(getbodyinbox())
This is my code so far with the parts that get the credentials removed. It gets the body of the most recent email without a label 'READ-BY-SCRIPT' that also has the label INBOX. How can I adapt it to get the sender of the email?
You can get the sender of an email in Message -> payload -> headers
You just need to match the header['name'] == 'From' and gets its equivalent header['value']
Sample Message Response Body (for Headers):
{
"payload": {
"partId": "",
"mimeType": "multipart/alternative",
"filename": "",
"headers": [
{
"name": "From",
"value": "User \u003cuser#email.com\u003e"
},
.....
{
"name": "Subject",
"value": "TEST EMAIL"
},
],
}
}
Sample Code:
headers = msg['payload']['headers']
for header in headers: # getting the Sender
if header['name'] == 'From':
msg_from = header['value']
break
Note:
Header sender value has this kind of format: "User \u003cuser#email.com\u003e"
You can get the sender's name by parsing the string from the start until \u003c tag, while you can get the sender's email by parsing the string that is enclosed in \u003c and \u003e tags.
In the below lambda function, I want to pass "Message2" variable in the HTML "BODY_HTML". Is there a way to pass my event Message2 in the HTML.
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
Message1 = event ["Message"]
print("Message_Received : ")
print(Message1)
Message2 = event ["Event"]
print("Event_Received : ")
print(Message2)
Message3 = event ["Sender"]
print("Sender : ")
print(Message3)
SENDER = "Redshift Pause Resuem Service <redshift#abc.com>"
RECIPIENT = Message3
#CONFIGURATION_SET = "ConfigSet"
AWS_REGION = "us-east-1"
SUBJECT = subject1
BODY_TEXT = ("Amazon SES Test (Python)\r\n"
"This email was sent with Amazon SES using the "
"AWS SDK for Python (Boto)."
)
BODY_HTML = **"""<html>
<head></head>
<body>
<p>I want to print here the variable "Message2"</p>
</body>
</html>
"""**
The character encoding for the email.
CHARSET = "UTF-8"
Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)
Try to send the email.
try:
#Provide the contents of the email.
response = client.send_email(
Destination={
'ToAddresses': [
RECIPIENT,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
},
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
)
# Display an error if something goes wrong.
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
Try using string formatting:
BODY_HTML = f"""<html>
<head></head>
<body>
<p>{Message2}</p>
</body>
</html>
"""
Or string concatenation:
BODY_HTML = f"<html><head></head><body><p>" + Message2 + "</p></body></html>"
Hi I am using urrlib2 to send some data and custom headers to a link. Am getting 500 internal server error. I have contacted the service, and they are saying the data(json data) is correct but there is some error in my python code. What am I doing wrong ?
Following is the code.
import urllib2,urllib
import json
PREPAYMENT_URL = "https://services.gharpay.in/rest/GharpayService/"
PREPAYMENT_USERNAME = "somename"
PREPAYMENT_PASSWORD = "somepass"
data = {
"customerDetails":{
"address": "ads",
"contactNo": "9663924147",
"email": "a#c.com",
"firstName": "akash",
"lastName": "deshpande",
"prefix": "Mr."
},
"orderDetails" : {
"pincode": "411036",
"clientOrderID": "21234",
"deliveryDate": "13-10-2013",
"orderAmount": "123",
"clientComments": "please be carefull",
"paymentMode": "Cash",
"productDetails": {
"productID": "21334",
"productQuantity": "1",
"unitCost": "123",
"productDescription": "tshirt"
},
"templateID": ""
},
}
def create(request):
function = 'createOrder'
url = PREPAYMENT_URL
url = url+ function
headers= {'username':PREPAYMENT_USERNAME,'password':PREPAYMENT_PASSWORD,'Content-type':'application/json'}
data1 = urllib.urlencode(data)
req = urllib2.Request(url,data1,headers)
try:
contents = urllib2.urlopen(req).read()
except urllib2.HTTPError as e:
error_message = e.read()
print error_message # this error message is being printed. It is showing 500 error.
Your code is perfect except for one teensy-weensy detail:
The header should be Content-Type, not Content-type.
Maybe try changing this header and let me know if it works!