Sending SMTP email with Django and Sendgrid on Heroku - django

I'm trying to send email using SMTP and sendgrid for a Django app. I'm able to send emails on my local server, but on my heroku app I get an "SMTPServerDisconnected" error saying "connection unexpectedly closed. Is there a way to send SMTP email with sendgrid once deployed to Heroku? I can't seem to find any documentation on this.
Here are my settings for email in settings.py:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'EMAIL_HOST_USER'
EMAIL_HOST_PASSWORD = 'EMAIL_HOST_PASSWORD'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'email#email.com'
SENDGRID_API_KEY='SENDGRID_API_KEY'
SENDGRID_PASSWORD='SENDGRID_PASSWORD'
SENDGRID_USERNAME='SENDGRID_USERNAME'
Please let me know what settings you use to send SMTP email. Thanks.

You need to go into your Sendgrid dyno. Navigate to Settings>API Keys.
Click on create API Key, at the time of writing this it is a blue button in the top right corner of the page.
copy the key that they generate for you and paste it somewhere on your local machine, also navigate back to your heroku page. Navigate to your app's Settings and click on "reveal config variables". You should now see key value pairs of all the environment variables. In the Key column add "SENDGRID_API_KEY" and in the value column add the key that you copied from the Sendgrid website. At this point the following python code should work:
sg = sendgrid.SendGridAPIClient(os.environ['SENDGRID_API_KEY'])
message = Mail(from_email='example#example.com', to_emails='example#example.com',
subject='Example Subject ', html_content='<strong>and easy to do anywhere, even with Python</strong>')
response = sg.send(message)
If you keep the response variable you can wrap the code in a try except block can try to catch errors. Sorry for the formatting I am still new to posting on stack overflow.

Related

How to make game use https when played via facebook and http when played from other domain

Our users play our Django game directly via our domain, cnamed to herokuapp.com. We request our assets via http.
We want to add our game to facebook, which requires using https. Heroku can handle this.
Using https requests: our game works on facebook but fails to load assets when accessed via our cnamed domain.
Can we make our game use https when played via facebook and http when played from our domain? What code must we add to settings.py?
We've tried this code in settings.py but it didn't work
Option 1:
import socket
if socket.gethostname().startswith('app'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
Option 2:
import socket
if socket.gethostname().startswith('edge'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
You could use protocol relative urls to save yourself from the pain of worrying about the protocol to use.
So the settings would look like:
STATIC_URL = "//d******1.cloudfront.net/"
and you can safely get rid of all the computation logic in your code snippet.

How do I set the from_email var

I'm trying to use Amazon's SES and the Django-ses app to send emails. It works locally but fails on the server, returning the SESAddressNotVerifiedError.
Inspecting the trace revealed that it's failing because the from_email var is set to webmaster#localhost. I've looked all over to find where I set this variable to my verified email address in AWS-SES.
Does anyone know how I am supposed to change the from_email var from webmaster#localhost to myemail#myemail.com?
Thanks,
Anthony
So it turns out that what I needed to change was this setting:
DEFAULT_FROM_EMAIL = 'My Domain < myEmail#myEmail.com >'
For everyone who is using Django-Registrations this is the default, but the reference to it is in registration/models.py, line 264 (the last line) if you want to change it, which I might unless it breaks, in which case, I'll report back.
Django default_from_email name
Thanks to Ashok for this solution

Sending email not working on heroku

I have this function in forms.py. There is currently no email specifications in my settings.py.
def send_email(FROM_NAME,FROM,TO,SUB,MSG,EXISTING_EMAIL,EXISTING_PASSWORD):
FROMADDR = "%s <%s>" % (FROM_NAME, FROM)
LOGIN = EXISTING_EMAIL
PASSWORD = EXISTING_PASSWORD
TOADDRS = [TO]
SUBJECT = SUB
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += MSG+"\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I call it my views.py like so
send_email('my_name','from_me#gmail.com','to_som1#gmail.com','my subject','mymessage','my_existing_email#gmail.com','password_to_existing_email')
This works locally. I have tested it with yahoomail and gmail. But when I upload to heroku it gives the error "(535, '5.7.1 Please log in with your web browser and then try again. Learn more at\n5.7.1 support.google.com/mail/bin/answer.py?answer=78754 et6sm2577249qab.8')"
Can anyone help?
You want to use this:
FROMADDR = "%s <%s>" % (your_name, your_email)
You shouldn't be building emails with string interpolation, that's a good way to get your site used to send spam via header injections. See my answer here for details on how to construct emails securely.
Generally speaking, when formatting from addresses, you should use the format Display Name <email#example.com>. See RFC 5322 for details.
Have you read the page linked to in the error message?
If you're repeatedly prompted for your username and password, or if
you're getting an 'invalid credentials' or 'web login required' error,
make sure your password is correct. Keep in mind that password are
case-sensitive.
If you’re sure your password is correct, sign in to your account from
the web version of Gmail instead at http://mail.google.com
In most cases signing in from the web should resolve the issue
Here is what worked for me. After getting the error Please log in with your web browser and then try again. Learn more etc. when trying to send email from my web application, I logged in to the email via browser from my local computer.
After I logged in, there was a yellow notification bar on top which asking me if I want to allow external application access my mail. I confirmed this and Google asked me to log in to the account from the application within the next 10 mins. This will white-list the application.

django socialauth twitter , google oauth , facebook does not work

This is my first post, and I have a problem I could not make it work django OMAB socialauth of three things I just need to google, facebook, and twitter, google works well with open id, but not much twitter and I put in my
settings. py:
TWITTER_CONSUMER_KEY = '00' this is no real
TWITTER_CONSUMER_SECRET = '00' this is no real
FACEBOOK_APP_ID = '' ihave no key
FACEBOOK_API_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
ORKUT_CONSUMER_KEY = ''
ORKUT_CONSUMER_SECRET = ''ihave no key
GOOGLE_OAUTH2_CLIENT_ID = ''
GOOGLE_OAUTH2_CLIENT_SECRET = ''
SOCIAL_AUTH_CREATE_USERS = True
SOCIAL_AUTH_FORCE_RANDOM_USERNAME = False
SOCIAL_AUTH_DEFAULT_USERNAME = 'socialauth_user'
SOCIAL_AUTH_COMPLETE_URL_NAME = 'socialauth_complete'
LOGIN_ERROR_URL = '/login/error/'
#SOCIAL_AUTH_USER_MODEL = 'app.CustomUser'
SOCIAL_AUTH_ERROR_KEY = 'socialauth_error'
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
FOURSQUARE_CONSUMER_KEY = ''
FOURSQUARE_CONSUMER_SECRET = ''
LOGIN_URL = '/login-form/'
LOGIN_REDIRECT_URL = '/'
LOGIN_ERROR_URL = '/login-error/'
I am using the example that comes in the zip of OMAB socialauth django , but not working.
When I created my twitter app, I wrote my domain www.sisvei.com , I am testing locally socialauth django ie 127.0.0.1:8000, then sign in with twitter sends me to this url:
http://127.0.0.1:8000/login/error/ and a message saying is the Incorrect authentication service
this happens with facebook and google oauth and oauth2
I'm new to django and I this much work comprising this part of django socialath hopefully help me, thank you very much.
You need to be more specific on "why it doesn't work". Where are you getting the errors?
When debugging a third-party oauth/openid app in Django, generally it boils down to:
configuration & keys - did you make sure to obtain all of the necessary API keys for the services you will be using, and to add them to your configuration?
urls - did you remember to add the necessary urlpatterns to your base urls.py file?
authentication setup on the server - often, you'll need to have a file available or respond with a specific header when the authentication service hits your server. Have you checked to make sure that is set up?
databases - have you run syncdb after installing the app? Are all the tables set up?
templates - if the third party app requires you to set up templates, do you have them set up?
custom views - are you using custom views? If so, try using the built-in views that came with the third party app first, to see if they work
After those are confirmed, you're going to want to be able to see what requests are taking place. Use the debugger included in Chrome/Safari, or get the web developer add-on for Firefox, and look at the network requests as they happen. Do you see HTTP responses other than 200 (say, 404, 500, 403, etc?) those mean that the services aren't responding correctly.
From your error, it looks like you have not correctly set up your callback URL on Twitter. It should be sending you to www.sisvei.com, not 127.0.0.1. Alternatively, check the URL when you get to the Twitter login page -- is the callback URL in the URL, and is it pointing to 127.0.0.1? Then Django is sending it the wrong callback URL.
Finally this:
I wrote my domain www.sisvei.com python does not support this
Is unclear. As far as I know, Python doesn't care what the domain is.
WAIT A MINUTE ...
Are you using runserver? Are you getting the following error?
Error: "www.sisvei.com" is not a valid port number or address:port pair.
If so, there is an easy fix! Just run it like so:
python manage.py runserver www.sisvei.com:80
That should resolve your error if that's what's happening. You're probably running it as
python manage.py runserver 127.0.0.1
127.0.0.1 is a reserved IP address that points back to localhost, your own computer. As a result, it is not possible to use it for authentication or any other purpose outside of programs running on your own machine. See this article for more info.
I'm not sure, but I might be having similar problems, oscar. For me, SocialAuth was generating an AuthenticationURL for facebook, foursquare and hotmail, but not for google, twitter or any of the other address it supports. I think it may be something wrong with the API, so I posted an issue on the social-auth google group...you may want to check there to see if anyone updates!!
https://code.google.com/p/socialauth/issues/detail?id=282&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Modified

How can I get Django on Google App Engine to automatically email server 500 errors to Admins?

When my App raises a server 500 error, I'm not receiving the automatic Django email that it should be sending: https://docs.djangoproject.com/en/1.3/howto/error-reporting/
I'm using the Google App Engine Django Helper at http://code.google.com/p/google-app-engine-django/
In my settings.py file:
DEBUG = False
ADMINS = (('Support', 'Support#******.com'),)
EMAIL_HOST = ''
SERVER_EMAIL = 'Support#******.com'
In the Google App Engine Dashboard, I've added Support#**.com (The same email in my settings.py) to the admins with the role of Viewer. I've tried changing the role to Developer.
I think the problem is this line:
EMAIL_HOST = ''
Since the Django docs say
In order to send e-mail, Django
requires a few settings telling it how
to connect to your mail server. At the
very least, you’ll need to specify
EMAIL_HOST. . .
But, the there are comments in the settings.py file that came with the google-app-engine-django project that say
# Ensure that email is not sent via SMTP by default to match the standard App
# Engine SDK behaviour. If you want to send email via SMTP then add the name of
# your mailserver here.
EMAIL_HOST = ''
Make sure you specify the 'SERVER_EMAIL' (https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SERVER_EMAIL) in your settings. Otherwise the emails will be sent from "root#localhost" and AppEngine won't send them.