SparkPost: At least one valid recipient is required python/django API - python

I have a problem sending email with SparkPost:
My code is as follow:
from configurations.global_configs import site_base_url
from media.settings import SPARKPOST_API_KEY
from sparkpost import SparkPost
import traceback
def welcome_email(user_profile):
try:
user_profile.confirmation_key = user_profile.generate_key()
user_profile.save()
email_address = user_profile.user.email
print email_address
name = user_profile.user.first_name or email_address
email_confirmation_url = site_base_url + "api/account/signup/?ck=" + user_profile.confirmation_key
print email_confirmation_url
sp = SparkPost(SPARKPOST_API_KEY)
result = sp.transmissions.send(
recipients=[email_address],
template='welcome',
subject='this is my subject',
track_opens=True,
track_clicks=True,
substitution_data={
'email_validation_url': email_confirmation_url
},
transactional= True
)
return result
except:
traceback.print_exc()
but my code output is as follows and returns this error:
exampleemail#gmail.com
http://example.com/api/account/signup/?ck=1144f138439dc42e
Traceback (most recent call last):
File "./users_system/services/email_confirm.py", line 28, in welcome_email
transactional= True
File "/usr/local/lib/python2.7/dist-packages/sparkpost/transmissions.py", line 142, in send
results = self.request('POST', self.uri, data=json.dumps(payload))
File "/usr/local/lib/python2.7/dist-packages/sparkpost/base.py", line 26, in request
raise SparkPostAPIException(response)
SparkPostAPIException: Call to https://api.sparkpost.com/api/v1/transmissions returned 400, errors:
At least one valid recipient is required:
As you can see I have one recipient and I know that is valid because I sent test mail via sparkpost dashboard. But why I get this error "At least one valid recipient is required" ??!!! where is my problem

I found the answer, First I want to thank Sparkpost support team the issue was in email parser in spark module and the issue is created for solving it in my code I made this change to fix it:
recipients=[ dict(address=dict(email=email_address)) ],

Since you are using it as a django backend for your email, why don't you do this directly with the
from django.core.mail import send_mail
send_mail(
subject='hello from sparkpost',
message='Hello Rock stars!'
from_email='from#yourdomain.com',
recipient_list=['to#friendsdomain.com'],
html_message='<p>Hello Rock stars!</p>',
)
as mentioned in their official docs

Related

getting error on updating assignee and comment field in JIRA using python

I am using python to automate JIRA process, while doing I am unable to update Assignee and Comment fields.
While updating Assignee field, not getting any error, but the value is not updated properly, I am trying to assign from one user to other user, but it is getting updated as Unassigned
For comment field, getting an error.
Below is my code:
from atlassian import Jira
jira_instance = Jira(
url = "https://****.atlassian.net/",
username = "****#gmail.com",
password = "*******",
)
data = jira_instance.jql("project = PROJECTNAME AND status = 'IN PROGRESS' ORDER BY created ASC", fields=['description','assignee','reporter','comment'])
for i in range(len(data["issues"])):
test_data = data["issues"][i]
jira_instance.issue_update(test_data['key'], fields={'assignee':{'emailAddress': '#####gmail.com' }})
jira_instance.issue_update(test_data['key'], fields={'comment':{'comments': [{'body':'This is the comment'}]}})
Also tried using displayName instead of using emailAddress, but still same thing happens.
For comment field, got the below error:
Traceback (most recent call last):
File "c:/Users/path/jiratest.py", line 13, in <module>
jira_instance.issue_update(test_data['key'], fields={'comment':{'comments': [{'body':'This is the comment'}]}})
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\jira.py", line 891, in issue_update
return self.put(url, data={"fields": fields})
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\rest_client.py", line 341, in put
absolute=absolute,
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\rest_client.py", line 236, in request
self.raise_for_status(response)
File "C:\Users\path\AppData\Local\Programs\Python\Python37\lib\site-packages\atlassian\jira.py", line 3705, in raise_for_status
raise HTTPError(error_msg, response=response)
requests.exceptions.HTTPError
Please anyone help me out on this
You haven't said if you're using Jira Cloud or Server.
For Jira Cloud, you must set the assignee for an issue using that person's account ID, not their username or email address, so the request would look something like:
jira_instance.issue.update(assignee={'accountId': '5b10ac8d82e05b22cc7d4ef5'})
For adding a comment field, try something like this:
jira_instance.issue_add_comment(test_data['key'], 'This is the comment')
For updating the assignee, try this:
jira_instance.update_issue_field(test_data['key'], fields={"assignee": "####"})

Nonetype error in Sending an email to a teacher in python with SMTP

I used the code below to try to send an email to my teacher with my email and password:
import cs50
import smtplib
from email.message import EmailMessage
def main():
message = EmailMessage()
message.set_content("This email verifies run-check of ASSIGNMENT")
message['Subject'] = 'Assignment from ME'
message['From:'] = 'MY EMAIL'
message['To:'] = 'TEACHER'S EMAIL'
with smtplib.SMTP_SSL('smtp.gmail.com') as smtp:
smtp.login("MY EMAIL", "MY PASSWORD")
smtp.send_message(message)
sys.exit(0)
if(__name__ == "__main__"):
main()
However, I got an error message saying "TypeError: sequence item 0: expected str instance, NoneType found". Any idea what went wrong? It just took me 30 minutes of trying to get the login to work with Less Secure Apps...
Edit: No, the problem is not the third apostrophe in 'TEACHER'S EMAIL'. in the actual teacher's email there is not apostrophe yet I still get the TypeError problem.
Edit 2: Whole error code here:
Traceback (most recent call last):
File "/home/ubuntu/some folder idk/SMF29.py", line 48, in <module>
main()
File "/home/ubuntu/some folder idk/SMF29.py", line 42, in main
smtp.send_message(message)
File "/usr/local/lib/python3.9/smtplib.py", line 940, in send_message
from_addr = email.utils.getaddresses([from_addr])[0][1]
File "/usr/local/lib/python3.9/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found
Edit 3: seeing that some people surrounded their emails with <>, I tried that, and got a different error:
smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials l11sm1375218qkk.101 - gsmtp')
Which is confusing, because not only have I taken all the google steps including the enable less secure apps and verify device things, but I am only logged into that one account. Any idea what the problem could be?
Edit 4: turns out that was a stupid idea and after getting rid of the <>s around the emails and the colons in front of From and To it worked. I had previously accidentally forgotten to remove one pair of <> around my email after removing the colons.
As can be seen from the error traceback, specifically this line:
from_addr = email.utils.getaddresses([from_addr])[0][1]
You are missing the from_addr. The key for the From address is From, not From: (with a colon). Change the following line
message['From:'] = 'MY EMAIL'
to
message['From'] = 'MY EMAIL'
While you are at it, do the same for the To address as well.
See the docs for an example.

Sending Facebook message

Just trying to send a Facebook message with python.
Code:
import fbchat
from fbchat import Client
from fbchat.models import *
client = Client("my_username", "my_password")
#help(fb.Client.send)
#client.send(text="This is a test", thread_id="christopher.batey", thread_type=ThreadType.USER)
name = "christopher.batey"
friends = client.searchForUsers(name)
friend = friends[0]
uid = friend.uid
msg = "This is a test"
print(help(client.send))
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
Error:
Traceback (most recent call last):
File "main.py", line 13, in
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
TypeError: init() got an unexpected keyword argument 'thread_id'
I'm not familiar with the API but from the documentation, it looks like the proper call would be:
client.send(Message(text=msg), thread_id="christopher.batey", thread_type=ThreadType.USER)
where the message object is the first argument passed into send, followed by thread_id and thread_type.
I spent some time exploring this module a few years ago.
Quickly looking back at the github examples the the thread_id should be a number.
As such change
client.send(Message(text=msg, thread_id="christopher.batey", thread_type=ThreadType.USER))
to
client.send(Message(text=msg), thread_id=uid, thread_type=ThreadType.USER)
in your code. As your uid is that of the friend you want to send too.

Python: how to login on Youtube

So, I'm a bit confused on how I get past authentication on Youtube using Python and successfully login. I always get error 403 when I try to PragmaticLogin():
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
What do I have to do?
Update:
I think that it has to do with authentication. Do I need both developer_key and client_id? Where do I get each? I want to have rights to add comments to my videos etc.
Full error:
Traceback (most recent call last):
File "/home/bodhi32/Documents/bot.py", line 9, in <module>
client.ClientLogin(USERNAME, PASSWORD)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 833, in ClientLogin
self.ProgrammaticLogin(captcha_token, captcha_response)
File "/usr/lib/pymodules/python2.7/gdata/service.py", line 796, in ProgrammaticLogin
raise Error, 'Server responded with a 403 code'
gdata.service.Error: Server responded with a 403 code
ClientLogin is deprecated and has all sorts of errors. Don't use it.
Use OAuth2.
This sample should get you started:
https://github.com/youtube/api-samples/blob/master/python/my_uploads.py
Use your code but make sure you fill the developer_key and client_id fields ( check below how to get them).
yt_service = gdata.youtube.service.YouTubeService()
service.developer_key = 'MY Key'
service.client_id='My ID'
service.email = 'myemail#yahoo.gr'
service.password = 'mypassword'
service.source = 'my_program'
service.ProgrammaticLogin()
To obtain a youtube api go to
https://cloud.google.com/console/project and create a new project, then enable youtube.
Check this video for more info Obtaining a simple API key for use with the YouTube API

Difficulties with sending mail from GAE

I'm trying to send an email from within Google App Engine.
Whenever I try to send, I get a "Missing subject error".
When I run the code on the development server, it seems to work fine - the console output looks right and I'm taken to the page that I was expecting. But when I upload it and run it, I get:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__
handler.post(*groups)
File "/base/data/home/apps/spam-tool/1.349401522260793315/spam-tool.py", line 34, in post
body=cgi.escape(self.request.get('content')))
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 297, in send_mail
message.send(make_sync_call)
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 799, in send
raise ERROR_MAP[e.application_error](e.error_detail)
BadRequestError: Missing subject
But there's definitely a subject.
The code I'm using is:
> message = mail.EmailMessage(sender="admin_address#gmail.com>",
subject="test")
message.subject=self.request.get('content')
message.to = addr_to_send_to
message.body = self.request.get('content')
message.send()
(Yes, the subject is set twice... I've tried only setting it in one place or the other, and neither worked.)
Thanks in advance.
Try this:
def email_member(request):
to_addr = request.POST.get('email_to')
if not mail.is_email_valid(to_addr):
# Return an error message...
pass
else:
# note we can also send html email, e.g. html='<html><head></head><body>Hello world</body><html>'
mail.send_mail(
sender='admin#yourdomain.com',
to=to_addr,
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'))
I suggest you also send your email within the taskqueue, so you could setup something like this, you could pass over a unique parameter so that you are less likely to be hacked.
def mail_member_information(email_to, email_title, email_body):
taskqueue.add(
url = 'email_message',
params =
{
'email_to': email_to,
'email_title': email_title,
'email_body': email_body,
'valid_guid': 'ae9e34ca-a2c5-476e-b8be-72d807e3dc6b'
}
)
If you just want to send to the administrators then use this:
mail.send_mail_to_admins(sender='admin#yourdomain.com',
subject=request.POST.get('email_title'),
body=request.POST.get('email_body'),
html=request.POST.get('email_body'))
I don't know if it is what is throwing you off... but sender should be like this:
sender = '<admin_address#gmail.com>',
you are missing the '<' for the sender. Sometimes it throws an error downstream of where the actual error is.
Also, make sure the admin_address#gmail.com is a Google Account that has been added as a developer for that app.
I think you can send like this, make sure that sender is a admin of the app
from google.appengine.api import mail
mail.send_mail(sender="something#gmail.com",
to=email_valid.email,
subject="Please validate your email",
body=body_text,
html=htmlbody_text)

Categories