Timeout error in django send_mail program - python

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.

Related

Invalid address when sending mail via Django

I am trying to send mail via Django, but have an error: (501, b'5.1.7 Invalid address', '"emea\\\\sss1ss1"')
My EMAIL_HOST_USER = r'emea\xss1ss1'. As you can see my user consist \x so I am using r''. How to fix it, the real EMAIL_settings are correct.
my view.py
def home(request):
subject = 'Test mailing'
message = 'Hello world!!!'
email_from = settings.EMAIL_HOST_USER
recipient_list = ['smth#smth.com']
send_mail(subject,message,email_from,recipient_list)
return HttpResponse('Test mailing')
well if you want to send an email using Django, first you have to set some variables in settings.py.
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.zoho.com' # for zoho mail service. use smtp.gmail.com for Gmail.
EMAIL_HOST_USER = 'something#something.com'
EMAIL_HOST_PASSWORD = 'something'
DEFAULT_FROM_EMAIL = f'Your Name {EMAIL_HOST_USER}'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
then import send_mail function and settings:
from django.core.mail import send_mail
from your_project import settings
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [user_email, ],)

Sending emails with EmailMessage does not work when I deploy my application

I am developing an application with django. When I send emails locally with EmailMessage it works, but after deployment on heroku it doesn't work anymore. Here is the code in views.py
from django.template.loader import render_to_string
message = render_to_string("elec_meter/activate_email.html",
{
"user": user, "domaine": request.META['HTTP_HOST'],
"uid": urlsafe_base64_encode(force_bytes(user.id)),
"token": default_token_generator.make_token(user),
"password": password,"matricule": agent.matricule
}
)
email_to_send = EmailMessage("Activation du compte", message, to=[email])
email_to_send.send()
in settings.py
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "my_email"
EMAIL_HOST_PASSWORD = "password"
EMAIL_USE_SSL = False
I need help please

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.

Server error 500 on sending email on Heroku

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})

Categories