How to intergrate sendgrid email function in kivy app? - python

I am trying to send an automatic email to a person who enters their name in my kivy app. I am trying to achieve this by using the Sendgrid email function, but the app and the function don't seem to be working together. The code is simple: I have a few text boxes for the user to input their name and email, and when they press the submit button they should get an email.
This is the sendgrid code for sending an email (it works)
message = Mail(
from_email='noreply.microloans#gmail.com',
to_emails=f'{email}',
subject=f"{name} is requesting your signature.",
html_content='Hello')
try:
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
except Exception as e:
print(e.message)
Here is the full code of my kivy app in pastebin: https://pastebin.com/guyU4PSb enter code here

Related

Sending emails from my django website, via sendgrid

I want to send account confirmation emails to all the users who sign up on my website, so it has to be an HTML email with the activation link. This is how i am trying to do it:
import os
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
def my_view(request):
current_site = get_current_site(request)
mail_subject = 'Welcome To IIITU Alumni Network'
to_email = email
ctx = {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
}
message = Mail(
to_emails = to_email,
from_email = '<my email address>',
subject = mail_subject,
#I made this html page specifically for sending confirmation email
#I am not sure if this is the correct way to do it
html_content = render_to_string('network/email.html', ctx)
)
try:
#I have this key as an environment variable
sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
#Now this is where the problem is
response = sg.send(message)
print(response.status_code)
print(response.body)
print(response.headers)
return HttpResponse("A confirmation Email has been sent to your Institute email address. Please Confirm Your email to complete your registration")
except Exception as e:
print(e.message)
return HttpResponse("The Server seems too busy!! Sorry for the inconvenience. Please try again later, or contact administrator if this problem persists.")
When this particular view is rendered, it throws the following error message:
'UnauthorizedError' object has no attribute 'message'
Since this doesn't send the emails via an SMTP server, according to my understanding i don't need to add anything to my settings.py file(i did add 'sendgrid' to my installed apps after i installed it using pip)Can someone please point out what i did wrong? I have been stuck on this for a while now...
Thank you for your time
I think this line is causing an error.
...
except Exception as e:
print(e.message)
...
Whatever exception is occuring, it doens't have message property.
Two solutions.
print(e)
remove try except block and try to figure out which exception is occurring and then catch that specifically.

Getting Error when trying to Generate password reset email link in django using firebase SDK

email = 'user#example.com'
link = auth.generate_password_reset_link(email, action_code_settings)
# Construct password reset email from a template embedding the link, and send
# using a custom SMTP server.
send_custom_email(email, link)
So I'm using this code from https://firebase.google.com/docs/auth/admin/email-action-links#python in django
and I'm getting this error:
NameError: name 'send_custom_email' is not defined
And nothing is mentioned in the documentation. So if anyone knows the solutions it would be great.
sg = SendGridAPIClient(os.environ["SENDGRID_API_KEY"])
html_content = f"""
<p>Hello,</p>
<p>Follow this link to reset password</p>
<p>{link}</p>
<p>If you didn't ask to reset the password, you can ignore this
email.</p>
"""
message = Mail(
to_emails=xyz#gmail.com,
from_email=Email('abc#gmail.com', "ABC System")
subject="Reset your password for ABC System",
html_content=html_content
)
try:
response = sg.send(message)
print(response.status_code)
except HTTPError as e:
print(e.message)
The above script is used for sending an email using Sendgrid.

Email confirmation in Flask fails

The below code successfully generates a token and sends a link to the user's inbox for confirmation. But when the user clicks on it, Flask is not recognizing the token it just created. Here is the error message:
"Got exception from ts.loads: 404 Not Found: The requested URL was not
found on the server. If you entered the URL manually please check
your spelling and try again."
The bottom line is that this is what should execute if I could make the confirmation procedure work properly:
return redirect(url_for('tutorials'))
But, as you can piece together by noting the error message that is coming out of #app.errorhandler(404), something is going wrong. I'm really stuck. These tests are being done way before the max_age of 86400 seconds is reached. Any help would be much appreciated!!!
from itsdangerous import URLSafeTimedSerializer
ts = URLSafeTimedSerializer(SECRET_KEY, salt='email-confirm-key')
#app.route('/signup', methods=['GET', 'POST'])
def signup():
#skipping unrelated lines of code
token = ts.dumps(form.email.data, salt='email-confirm-key')
subject = 'subject goes here'
msg = Message(subject=subject, sender='name#email.com', recipients=form.email.data.split())
link = url_for('confirm_email', token=token, _external=True)
msg.html = render_template("email_confirmationemail.html", link=link, name=request.form['first_name'])
with app.app_context():
mail.send(msg)
return redirect(url_for('checkyouremail'))
#app.route('/confirmemail/<token>')
def confirm_email(token):
try:
email = ts.loads(token, salt='email-confirm-key', max_age=86400)
#skipping unrelated lines of code
return redirect(url_for('tutorials'))
#app.errorhandler(404)
def not_found(e):
print('Got exception from ts.loads: {}'.format(e))
return render_template('404.html')
In models.py, my __init__ method for the User class has this line:
self.email = email.lower()
When users create a profile on a phone, their email address often starts with an uppercase letter.
So I just needed to change
token = ts.dumps(form.email.data, salt='email-confirm-key')
to
token = ts.dumps(form.email.data.lower(), salt='email-confirm-key')
so that the email held in the token matched with the email in the database when the user clicked on the confirmation link I sent them. (In short, adding .lower() as shown above in my call do dumps solved my problem).

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)

Update status Facebook using Python

I'm trying the solve problem update status using facebook API with pyfacebook. So I look at here Update Facebook Page's status using pyfacebook and I think doesn't work anymore.
Well, finally I solve the problem:
#!/usr/bin/python
import facebook
# Replace these with your app's credentials
api_key = 'YOUR_API_KEY'
secret_key = 'YOUR_SECRET_KEY'
client = facebook.Facebook(api_key, secret_key)
client.auth.createToken()
client.login()
print '[*] Please login / give permission application to access you . Then press enter key to continue...',
raw_input()
try:
client.auth.getSession()
client.request_extended_permission("publish_stream", popup=False)
raw_input()
cek = client.status.set("Testing update status using facebook API with pyfacebook")
except facebook.FacebookError, e:
print "ERROR", e

Categories