Mandrill API E-mail queue with sinatra - api

Trying to get form to send e-mail to Mandrill api. My email keeps getting queued and will not send.
post '/my-handling-form-page' do
m = Mandrill::API.new
message = {
:subject => "Hello from the Mandrill API",
:from_name => "#{params[:name]} #{params[:email]}",
:text => "Hi message how are you?",
:to => [
{
:email => "anonymous#gmail.com",
:name => "Recipient1"
}
],
:html => "<html>#{params[:msg]}</html>",
:from_email => "anonymous#gmail.com"
}
sending = m.messages.send message
puts sending
erb :index
end
Error says:
{"email"=>"anonymous#gmail.com", "status"=>"queued", "_id"=>"216c30f42ee849e2a70528e3d4f9774f", "reject_reason"=>nil}
Help would be appreciated.

From the Mandrill docs:
Why does a delivered message say "queued"?
Mandrill automatically tracks and records the SMTP response we receive
from recipient mail servers for each email you send. Some successfully
delivered emails will include a "queued" notation in the SMTP response
such as 250 OK; queued as 12345. The email has still been delivered to
the recipient as expected, but may require additional processing
before it lands in the recipient's mailbox. For example, most times
Mandrill can send email much faster than recipient servers are able to
accept or process it. In many cases, things like the time of day and
overall email traffic to that ISP or recipient server can affect how
quickly they're able to receive and process your email.
Your code seems fine. Looks there could be an issue with the recipient's server.

A Response Mail From Mandrill :
Thanks for reaching out. In this case, it appears that the API call being passed to Mandrill contains several invalid parameters - however, since you're also passing us an attachment array in that API call, you won't see the response indicating that it's an invalid API call.
Whenever Mandrill receives an attachment, we will always return a response of "Queued," as our systems will set that message aside to scan the attachment for viruses/malware before we process it in any other way. This means that, if something else is wrong with the API call, you won't be alerted, and it will "silently" fail.
It looks as though you've included several parameters from our default API docs, but those are intended to show users how those parameters would be included.
**"subaccount"**: "customer-123",
and
**"ip_pool"**: "Main Pool",
Will both cause this API call to fail, as you're specifying options that don't exist within your account. I would recommend that you go through your API code and remove anything that you aren't using. For reference, the minimum API call required to send an email would look like:
{
"message": {
"html": "<html content>",
"subject": "<subject>",
"from_email": "<sender email address>",
"from_name": "<sender name>",
"to": [
{
"email": "<recipient email address>",
"name": "<recipient name>",
"type": "to"
}
],
"headers": {
"Reply-To": "<reply-to address>"
}
},
"async": false,
"ip_pool": null,
"send_at": null,
"key": "<valid API key>"
}
So after this valuable response this what that work in Django for me :)
def send_mail_msg():
import mandrill
try:
mandrill_client = mandrill.Mandrill('xxxxxxxxxxxxxxx')
message = {
# 'attachments': [{'content': 'ZXhhbXBsZSBmaWxl',
# 'name': 'myfile.txt',
# 'type': 'text/plain'}],
'auto_html': None,
'auto_text': None,
# 'bcc_address': 'message.bcc_address#example.com',
'from_email': 'xxxxx#xxxx.com',
'from_name': 'Example Name',
'global_merge_vars': [{'content': 'merge1 content', 'name': 'merge1'}],
'google_analytics_campaign': 'gaurav#nexthoughts.com',
'google_analytics_domains': ['example.com'],
# 'headers': {'Reply-To': 'message.reply#example.com'},
'html': '<p>Example HTML content</p>',
'images': [{'content': 'ZXhhbXBsZSBmaWxl',
'name': 'IMAGECID',
'type': 'image/png'}],
'important': False,
'inline_css': None,
'merge': True,
'merge_language': 'mailchimp',
# 'merge_vars': [{'rcpt': 'recipient.email#example.com',
# 'vars': [{'content': 'merge2 content', 'name': 'merge2'}]}],
'metadata': {'website': 'www.example.com'},
'preserve_recipients': None,
'recipient_metadata': [{'rcpt': 'recipient.email#example.com',
'values': {'user_id': 123456}}],
'return_path_domain': None,
'signing_domain': None,
# 'subaccount': 'customer-123',
'subject': 'example subject',
'tags': ['password-resets'],
'text': 'Example text content',
'to': [{'email': 'xxxxx#xxxx.com',
'name': 'Recipient Name',
'type': 'to'}],
'track_clicks': None,
'track_opens': None,
'tracking_domain': None,
'url_strip_qs': None,
'view_content_link': None}
result = mandrill_client.messages.send(message=message, async=False, ip_pool='Main Pool')
# send_at=str(datetime.datetime.now().time()))
'''
[{'_id': 'abc123abc123abc123abc123abc123',
'email': 'recipient.email#example.com',
'reject_reason': 'hard-bounce',
'status': 'sent'}]
'''
return result
except mandrill.Error as e: # Mandrill errors are thrown as exceptions
print 'A mandrill error occurred: %s - %s' % (e.__class__, e)
# A mandrill error occurred: <class 'mandrill.UnknownSubaccountError'> - No subaccount exists with the id 'customer-123'
raise`

According to Mandrill api:
subaccount
the unique id of a subaccount for this message - must already exist or will fail with an error.
(At least for me the test start working after removing that field).
Mandrill definitely should improve their response errors.

Related

How to use Ethereum RPC API to swap tokens?

I am trying to code a client for swapping tokens through BSC chain (I really don't want to use web3 libraries) using Ethereum API. So learned some stuff from Ethereum RPC API documentation, but i can't really understand what are the steps for sending Raw Signed transaction. So here is my example payload:
data = {"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [
{
'from': address,
'to': self.router_address,
'gas': hex(gas),
'gasPrice': hex(gasPrice),
'value': hex(ETH_amount),
'data': query,
"nonce": await self.getTransactionCount(address)
}],
"id": _id}
And of course necessary header {"Content-Type": "application/json"}
The data field (query variable) basically was taken from this transaction. If you scroll down, you can see the original payload, which of course was successfully processed, because the operation was created with PancakeSwap. But when i send the same (even with modified deadline parameter) i get the this:
{'jsonrpc': '2.0', 'id': 1, 'error': {'code': -32000, 'message': 'unknown account'}}
Obvioulsy somewhere should be done signing function, but i just don't know how to make it. Can somebody help me? How do I process the data and make requests so that the swap succeeds? (From BNB to BUSD, for example - without approving step).

Cant send discord messages via API

I wrote this code in python to send a message = "message" to my own channel (with 3 members). It is supposed to complete it and print "200" as a success, it instead doesn't write "200", it writes "400" and doesn't send anything to the channel.
In this question I removed the channel and the token and wrote "ggbro" instead.
import requests
payload ={
"contant": 'message'
}
header ={
"authorization": 'GGBRO'
}
r = requests.post('https://discord.com/api/v9/channels/GGBRO/messages',data=payload, headers=header)
print(r.status_code)

Resolve Discord-Tag get Discord-ID programmatically

I want to add a function to my userprofiles where users can enter their discord tag and if they do so, I want to resolve this to a link to their discordprofile so that users only have to click on the discordtag to open the profile in discord.
For that I need the ID. What Request do I need to send to the discord api in order to get the user ID for the entered tag?
After some experiments with discord friend sending. I found out that you can actually obtain user the user ID by sending friend request.
Here's how:
Make a add request friend request to example#1234
Make another request to the relationship(AKA friend) list to get all pending "friends" with ID, username, avatar... This list actually contains all of the actual friends from the person that sent a friend request.
To find the requested username in the friend list, all you need is a loop searching for the corresponding username + discriminator.
Output the ID(if that's what you wanted), after the username and discriminator match.
Delete the pending request.
Here's a python script I wrote that will output the ID of the user with inputs of username, discriminator, and an user token(used for sending an authorized friend request):
import requests
import json
# inputs
username = 'asdf'
discriminator = '1234'
TOKEN = 'ONLY USER TOKEN'
url = 'https://discord.com/api/v8/users/#me/relationships'
headers = {
"authorization": TOKEN
}
# setting up a payload for sending friend request.
payload = {
'username': username,
'discriminator': discriminator
}
requests.post(url, json=payload, headers=headers) # step 1
result = requests.get(url, headers=headers).json() # step 2
if hasattr(result, 'message'):
print('Invalid user token')
else:
user_id = None
for client in result: # step 3: a loop for finding the the username in the friend list
if f'{client["user"]["username"]}#{client["user"]["discriminator"]}' == f'{username}#{discriminator}':
user_id = client['id'] # step 4: save the user ID after finding it in the friend list
break
if user_id is None: # if no match is found then the user with that username and discriminator does not exist.
print('user not found')
else:
url = f'https://discord.com/api/v8/users/#me/relationships/{user_id}'
requests.delete(url, headers=headers) # step 5: delete the pending request
print(user_id) # print out the user ID
And here's the data structure of the requested json from step 2:
[
{
"id": "12345678901",
"type": 1,
"nickname": null,
"user": {
"id": "12345678901",
"username": "example1",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
},
{
"id": "12345678902",
"type": 1,
"nickname": null,
"user": {
"id": "12345678902",
"username": "example2",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
},
{
"id": "12345678903",
"type": 1,
"nickname": null,
"user": {
"id": "12345678903",
"username": "example3",
"avatar": "1234567890abcdef",
"discriminator": "1234",
"public_flags": 123
}
}
]
Downside:
You have to use an user token for sending the friend request.
Updates:
10/4/2020: Added in error detection for invalid token and invalid username.

SoftLayer REST API Cancellation Request

I would like to cancel a SoftLayer device on a certain date in the future and found the following SoftLayer_Billing_Item_Cancellation_Request::createObject.
What would the request url look like and what would the POST parameters look like if I was using json?
Thanks
This is a Rest example can help you:
Cancel Service - rest
To get billing item, please see:
SoftLayer_Virtual_Guest::getBillingItem
Also, this is a Python example:
"""
Cancel a Virtual Guest.
It cancels the resource for a billing Item. The billing item will be cancelled
immediately and reclaim of the resource will begin shortly.
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getObject
http://sldn.softlayer.com/reference/services/SoftLayer_Billing_Item/cancelService
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn#softlayer.com>
"""
import SoftLayer.API
from pprint import pprint as pp
# Your SoftLayer API username and key.
API_USERNAME = 'set me'
# Generate one at https://control.softlayer.com/account/users
API_KEY = 'set me'
virtualGuestId = 9923645
client = SoftLayer.Client(
username=API_USERNAME,
api_key=API_KEY,
)
try:
# Getting the billing item id
mask = 'mask.billingItem.id'
cci = client['SoftLayer_Virtual_Guest'].getObject(mask=mask, id=virtualGuestId)
billingItemId = cci['billingItem']['id']
try:
# Canceling the Virtual Guest
result = client['Billing_Item'].cancelService(id=billingItemId)
pp(result)
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to cancel the VSI faultCode=%s, faultString=%s'
% (e.faultCode, e.faultString))
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to get the billing item id from VSI faultCode=%s, faultString=%s'
% (e.faultCode, e.faultString))
Also there are a lot examples in other clients can help you:
Cancel Service - rest
Cancel service - Python
cancel service - php
cancel service-perl
References
SoftLayer_Billing_Item::cancelService
SoftLayer_Virtual_Guest::getBillingItem
SoftLayer_Virtual_Guest::getObject
This may be what are you looking for:
Post URL: https://api.softlayer.com/rest/v3.1/SoftLayer_Billing_Item_Cancellation_Request/createObject.json
Payload:
{
"parameters": [
{
"complexType": "SoftLayer_Billing_Item_Cancellation_Request",
"accountId": 321752,
"notes": "No notes provided",
"items": [
{
"complexType": "SoftLayer_Billing_Item_Cancellation_Request_Item",
"billingItemId": 25849466,
"scheduledCancellationDate": "5/15/2006"
}
]
}
]
}
I hope it helps
Regards
The answer that worked for me is the following:
https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/[deviceID]/getBillingItem.json
https://api.softlayer.com/rest/v3/SoftLayer_Billing_Item/[BillingItemID]/cancelServiceOnAnniversaryDate.json
Both are Get Requests.

Setting HTML as supported messageformat in UCWA

I have a functional ucwa client that only works with plain messages. According to the lync documentation, a PUT request is needed to change the supported modality and message format, and that an If-Match header is required to verify the request is not for an out-of-date status.
For example, a GET request to /ucwa/oauth/v1/applications/102628975647/communication will return
{
"9b5c7fdf-2c5f-462e-a4e3-39663f09301a": "please pass this in a PUT request",
"supportedModalities": [],
"supportedMessageFormats": [
"Plain"
],
"_links": {..},/*ommitted for brevity */
"rel": "communication",
"etag": "3010254294"
}
I PUT back this, with an If-Match: 3010254294 header:
{
"9b5c7fdf-2c5f-462e-a4e3-39663f09301a": "please pass this in a PUT request",
"supportedModalities": [],
"supportedMessageFormats": [
"Plain", "Html"
],
"rel": "communication",
"etag": "3010254294"
}
But I consistently get a 428 PreconditionRequired error, which, according to documentation, means that I am missing the If-Match header. Various combinations of ETag and If-Match also fail. What is the proper format for this request?
I remember running into this issue when I was trying to figure out why I could not receive HTML-formatted messages. The issue being that you appear to have the data correct except the If-Match header is very particular in that it would only work for me when I had the value quoted and it may/may not work for single quotes.
If-Match: "3010254294"
Relevant Fiddler Trace: UCWA Html Messaging.saz