Server error 500 on sending email on Heroku - python

I have a Django project. The user fills the form and then I receive a notification about new order. Localy, on my computer everything is ok. I deploy my application on Heroku and on the site I cannot send emails. I receive error 500.
This is my code:
settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL='sitename'
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .forms import OrderForm
def contact(request):
company='no company'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
company=form.cleaned_data['company']
try:
msg_plain = render_to_string('../templates/publicity_agency/email.txt', {'company':company})
msg_html = render_to_string('../templates/publicity_agency/email.html', {'company':company})
msg_plain_client = render_to_string('../templates/publicity_agency/email_client.txt')
msg_html_client = render_to_string('../templates/publicity_agency/email_client.html')
send_mail('New order',msg_plain,'Notification <myemail#gmail.com>', ['myemail#gmail.com'], html_message=msg_html)
send_mail('Order',msg_plain_client,'Order <myemail#gmail.com>', [email], html_message=msg_html_client)
except BadHeaderError:
return HttpResponse('Invalid header found')
return redirect('contact')
else:
form=OrderForm()
return render(request, 'publicity_agency/contacts.html', {'company':company})

Related

Timeout error in django send_mail program

I am doing a send_mail function in django and connected mysql database with it to store the name and subject values. I am using the smtp backend server to connect the mail and django. The port used is 587.
This is my settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mail_test',
'USER': 'root',
'PASSWORD': '',
'HOST':'localhost',
'PORT':'3306',
'OPTIONS':{
'init_command':"SET sql_mode='STRICT_TRANS_TABLES'"
}
}
}
----
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'swarai.bot#gmail.com'
EMAIL_HOST_PASSWORD = 'pfxbswfjgligavgb'
** This is my views.py**
from django.views.generic import FormView, TemplateView
from .forms import EmailForm
from django.urls import reverse_lazy
from mailapp.models import Email
from django.shortcuts import render
class MailView(FormView):
template_name = 'index.html'
form_class = EmailForm
success_url = reverse_lazy('mailapp:success')
def form_valid(self, form):
# Calls the custom send method
form.send()
return super().form_valid(form)
def registered(request):
name = request.POST['name']
email = request.POST['email']
inquiry = request.POST['inquiry']
message = request.POST['message']
person = Email(name=name, email=email, inquiry=inquiry, message=message)
person.save()
return render(request, 'success.html')
class MailSuccessView(TemplateView):
template_name = 'success.html'
I am getting timeout error whenever I submit the page. I tried to add the port 587 using control panel. But then also, I am getting the same error. I don't know whether this error is from port or database side. Please help me guys. This is my first project using django.

Not able to send email to sendgrid python

my send_mail code
from rest_framework.views import APIView
from middleware.response import success, bad_request
from user.serializer.dao import SendEmailDao
from core.models import EmailLeadLogs
from util.email import send_mail
class SendEmailView(APIView):
def post(self, request):
attributes = SendEmailDao(data=request.data)
if not attributes.is_valid():
return bad_request(attributes.errors)
email_lead_logs = EmailLeadLogs(**attributes.data["meta"])
email_lead_logs.subject = attributes.data["subject"]
email_lead_logs.save()
send_mail(attributes.data["email"].split(","), attributes.data["subject"], attributes.data["message"])
return success({}, "email send successfully", True)
This is the error i am getting, I am trying to use it from drf
error
It's important to make sure your email settings are wired up correctly in settings.py. Here are the options I use when configuring Sendgrid (you may not need them all):
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'myemail#email.com'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_SUBJECT_PREFIX = 'Hello'
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = 'optional'
EMAIL_HOST_PASSWORD is the API key that Sendgrid gives you.

Send email with Sendgrid in Django

I'm trying to send emails from a Django app using Sendgrid. I've tried many configurations, but I still doesn't get any email on my Gmail account. You can see my configurations bellow:
settings.py:
SEND_GRID_API_KEY = 'APIGENERATEDONSENDGRID'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mySENDGRIDusername'
EMAIL_HOST_PASSWORD = 'myEMAILpassword' #sendgrid email
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'MYEMAIL' #sendgrig email
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import ContactForm
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import get_template
def index(request):
return render(request, 'index.html')
def contact(request):
success = False
form = ContactForm(request.POST)
if request.method == 'POST':
name = request.POST.get("name")
email = request.POST.get("email")
message = request.POST.get("message")
subject = 'Contact from MYSITE'
from_email = settings.DEFAULT_FROM_EMAIL
to_email = [settings.DEFAULT_FROM_EMAIL]
message = 'Name: {0}\nEmail:{1}\n{2}'.format(name, email, message)
send_mail(subject, message, from_email, to_email, fail_silently=True)
success = True
else:
form = ContactForm()
context = {
'form': form,
'success': success
}
return render(request, 'contact.html',context)
Do you guys know what could be happening? I can get the email locally and I can see it in the terminal, but no email can be sent at all.
I struggled a bit when trying to set up the sendgrid with Django using SMTP. What worked for me is the following:
settings.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'sendgrid-api-key' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'your-email#example.com' # this is the sendgrid email
I used this configuration, and it worked properly, and I strongly suggest using environment variables to fill EMAIL_HOST_PASSWORD and DEFAULT_FROM_EMAIL, so the code will be as follows:
import os # this should be at the top of the file
# ...
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD", "")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", "")
Then, when sending an email I used the following code:
from django.conf import settings
from django.core.mail import send_mail
send_mail('This is the title of the email',
'This is the message you want to send',
settings.DEFAULT_FROM_EMAIL,
[
settings.EMAIL_HOST_USER, # add more emails to this list of you want to
]
)
Try adding these to right bellow the your declaration in settings
SENDGRID_SANDBOX_MODE_IN_DEBUG=False
SENDGRID_ECHO_TO_STDOUT=False
DO this settings on your settings.py file
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_SANDBOX_MODE_IN_DEBUG = False
FROM_EMAIL = 'youremail#gmail.com' # replace with your address
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY')
dont use debug true if you run this on your local server.
This is working for me, I think the SendGrid guide might be missing the DEFAULT_FROM_EMAIL which seems necessary if you haven't set it up on their website.

Login Django not working

I just created a login with Django, but it doesn't want to work. The script should redirect to start.html if the user login correctly. But Django just reload the page writing the username and the passwort in the url.
view.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.views.generic import View
class Index(View):
def get(self, request):
return render(request, "index.html")
def user_login(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('^start/')
else:
return HttpResponseRedirect('^err/')
else:
print ("Invalid login details")
return HttpResponseRedirect('^impressum/')
urls.py of the project:
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from alarm.views import *
from impressum.views import *
from login.views import *
urlpatterns = [
url(r'^$', Index.as_view()),
url(r'^admin/', admin.site.urls),
url(r'^start/', start.as_view()),
url(r'^terms/', impressum.as_view()),
url(r'^err/', error404.as_view())
]
Whats wrong with this?
Full code: https://github.com/Croghs/stuport
Thanks for every help and sorry for bad english
Croghs
Change <form type="post"> to <form method="post"> in index.html.
Class-based views don't recognise a "user_login" method. It should be called just "post".

Django. Sending email with an application

I started a new application gmail and configured settings in settings.py with my gmail account
I'm new in django and I don't know how to send emails to my website users
I would like to create a link that when I open it my user will get a message from me
I have edited views.py but I don't know what my function "wyslij" should return
from django.shortcuts import render
from django.core.mail import send_mail
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from userprofile.models import UserProfile
#user_passes_test(lambda u: u.is_superuser)
# Create your views here.
def wyslij(request):
# Create the HttpResponse object with the appropriate PDF headers.
uzyt = UserProfile.objects.all().order_by('user_id')
for z, uzyt in enumerate(UserProfile.objects.all()):
send_mail('The exam is comming', 'Hi, Your exam will be tomorrow!', 'santa.claus.for.grace#gmail.com', [uzyt.email], fail_silently=False)
return response
In urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^accounts/wyslij/$', 'gmail.views.wyslij'),
)
In settings.py, you have to add these liner:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xxxxxxxxxxx#gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxx'
EMAIL_PORT = 587 #or try with 25
https://docs.djangoproject.com/en/1.7/topics/email/
be sure to name your EMAIL variables and .gitignore your settings file

Categories