I'm trying to send a email via smtp using Django. When I try to send the email, I do not get any error, but my application does not respond and it keeps waiting on to send the email, but obviously it does not send nothing.
I have tried with smtp gmail and smtp hotmail, but it is not working. I have already checked my Windows firewall, and again it is not working. I have tried to send the email using Python shell but it does not send nothing.
I think that I have tried almost everything that I saw on the other posts here in Stack Overflow.
settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.office365.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail#hotmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
SERVER_EMAIL = EMAIL_HOST_USER
mails.py:
from django.conf import settings
from django.template.loader import get_template
from django.core.mail import EmailMultiAlternatives
class Mail:
#staticmethod
def send_complete_order(orden, user):
subject = 'order sent'
template = get_template('orders/mails/complete.html')
content = template.render({
'user': user
})
message = EmailMultiAlternatives(subject, 'Testing',
settings.EMAIL_HOST_USER, [user.email])
message.attach_alternative(content, 'text/html')
message.send()
views.py:
#login_required(login_url='login')
def complete(request):
cart = get_or_create_cart(request)
order = get_or_create_order(cart, request)
if request.user.id != order.user_id:
return redirect('carts:cart')
order.complete()
Mail.send_complete_order(order, request.user)
destroy_cart(request)
destroy_order(request)
messages.success(request, "order complete")
return redirect('index')
Create a secure SSL context
context = ssl.create_default_context()
try:
with smtplib.SMTP_SSL(smtp_mail, port, context=context) as server2:
server2.login(your_mail, passwort)
server2.sendmail(mail_from, mail_to, message.as_string())
print("Successfully sent email")
Related
I am trying to create a contact form in Django that actually sends emails for real. Can i put all the email configs in the views.py file itself? I want to do that because i want only the legitimate owners of emails to actually send emails. I do not people to send me emails using their friends email.
Yes obviously you can, but make sure you have your email credentials stored in your settings.py file safely
What is ideal is to save your email credentials as environment variables
In your settings.py File
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = "from#example.com"
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# If you are using any other smtp host.
# Search documentation for other smtp host name and port number
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = "from#example.com"
EMAIL_HOST_PASSWORD = "SUPER_SECRET_PASSWORD"
In your view that you want to use to send email
views.py
from django.core.mail import EmailMessage
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
email = EmailMessage(subject=subject,body=body,to=[to])
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")
If you want to send html template or image using email Email Template via your django app
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from YourProject.settings import EMAIL_HOST_USER
def email_send_view(request):
if request.method == "POST":
# Get email information via post request
to_email = request.POST.get("to", "")
subject = request.POST.get("subject", "")
message = request.POST.get("message", "")
if to_email and message:
# Gets HTML from template
# Make sure in this case you have
# html template saved in your template directory
html_message = render_to_string('template.html',
{'context': 'Special Message'})
# Creates HTML Email
email = EmailMultiAlternatives(subject,
from_email=EMAIL_HOST_USER,
to=[to])
# Send Email
email.attach_alternative(html_message, "text/html")
email.send()
# Complete your view
# ...
return redirect("REDIRECT_VIEW")
I am writing django application and trying to send email using it I have "Access to low security app" in gmail enabled and django setting are given below which I think are right. but I am still getting error as mentioned it title. I dont know the problem but I know I am not getting logged in to send email.
Edit 1: I have made two changes first in settings.py and second in views.py in views.py I replaced email entered by user to mine(syedfaizan824#gmail.com) and settings.py DEFAULT_EMAIL_FROM is changed form testing#example.com to syedfaizan824#gmail.com
searched on internet and find out that gmail does not allow low security app to login by default but I turned it off in setting of gmail. find out that my email backend was wrong so made it right. fail silently is False.
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = 'syedfaizan824#gmail.com'
EMAIL_HOST_USER = 'syedfaizan824#gmail.com'
EMAIL_HOST_PASSWORD = '******'
views.py
def post(self, request, *args, **kwargs):
form = contact(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
phone = form.cleaned_data['phone']
organization = form.cleaned_data['organization']
message = form.cleaned_data['message']
ref_code = form.cleaned_data['ref_code']
plan = form.cleaned_data['plan']
message = message + ref_code
send_mail(
'from website' + name + " " + organization,
message,
'syedfaizan824#gmail.com',
['syedfaizan824#gmail.com'],
fail_silently=False,
)
print("sent")
else:
#print('something is wrong with forms!')
return render(request, self.template_name, self.context)
Error message is ConnectionRefusedError WinError[10061]. and statement of error is : No connection could be made because the target machine actively refused it. which means I am not getting logged in.
change
EMAL_HOST = 'smtp.gmail.com'
to
EMAIL_HOST = 'smtp.gmail.com'
You are missing the 'I' character in the word 'EMAIL'
I am trying to send email from the user who is logged in to an account which I have given bilalkhangood4#gmail.com. But I have typed it manually. There could be more accounts means more users from which I want to send. But how could I send email from just those users who are logged in? Basically it is an APP where a user will click on withdraw button to request and send mail to official admin account.
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'bilalkhangood4#gmail.com'
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
ACCOUNT_EMAIL_VERIFICATION = 'none'
EMAIL_USE_SSL = False
views.py
from django.contrib.auth.models import User
def ViewSendEmail(request):
send_mail('Hello from Bilal Khan',
'Hello there, This is an automated message.',
'bilalkhangood6#gmail.com', #FROM
['bilalkhangood4#gmail.com'], #TO
fail_silently=False)
return render(request, 'nextone/email_send.html')
use request.user.email to access the email address of logged in user.
update your code with following:
def ViewSendEmail(request):
send_mail('Hello from Bilal Khan',
'Hello there, This is an automated message.',
request.user.email, #FROM
['bilalkhangood6#gmail.com'], #TO
fail_silently=False)
return render(request, 'nextone/email_send.html')
I've been trying to let users send email to my personal account via form. At first it was showing me
socket.gaierror: [Errno 11004] getaddrinfo failed
error which I solved by installing and configuring hMailServer in my device. Now when I try to send mail by my friend's email it send email by my own account instead. When I removed MAIL_HOST_USER = 'my_email' from settings file, it shows
smtplib.SMTPSenderRefused
error as mentioned in title. Any suggestions or related links will be appreciated.
My code is:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 25
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my_email'
EMAIL_HOST_PASSWORD = 'my_password'
EMAIL_USE_TLS = True
views.py
class contact(View):
def post(self, request):
form = ContactForm(request.POST)
if form.is_valid():
if send_mail(subject = form.cleaned_data['title'], message = form.cleaned_data['content'], from_email = form.cleaned_data['contact_email'], recipient_list = ['my_email'], fail_silently=False):
return render(request, 'index.html', {'form': form, 'message': 'Message delivered successfully', 'error':'', 'email_sent': 1 })
else:
return render(request, 'index.html', {'form': ContactForm(), 'error': form.errors})
Gmail, like more or less any other email provider or correctly configured mail server, does not allow you to set an arbitrary From address. An email server that allows this would be abused by spammers and quickly find itself on a spam blacklist.
What you can do is set my_email as sender and add a Reply-To header with the email address provided through the form.
You have to create an EmailMessage instance and call send():
from django.core.mail import EmailMessage
...
email = EmailMessage(
subject=form.cleaned_data['title'],
message=form.cleaned_data['content'],
from_email='my_email',
recipient_list=['my_email'],
reply_to=form.cleaned_data['contact_email']
)
sent = email.send(fail_silently=False)
if sent:
return render(request, 'index.html', {'form': form, 'message': 'Message delivered successfully', 'error':'', 'email_sent': 1 })
Note that Gmail has some limits on the number of emails you can send this way. Make sure you don't accidentally block your account.
N.B., you can configure gmail to relay messages on behalf of any sending address in a google apps organization (powered by gmail), but as Daniel Hepper noted, this is not the default for a personal gmail address. That said, I would wager that the OP's problem is likely that the port setting is incorrect. In gmail, the port setting should be 465 or 587 for TLS-using SMTP.
I would like to send email in Django 1.10.
This is the snippet code in settings.py file.
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my email address'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
This is the snippet code in views.py file which is responsible for sending email.
from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings
from .forms import contactForm
def contact(request):
form = contactForm(request.POST or None)
if form.is_valid():
name = form.cleaned_data['name']
comment = form.cleaned_data['comment']
subject = 'Message form MYSITE.com'
message = '%s %s' %(comment, name)
emailFrom = form.cleaned_data['email']
emailTo = [settings.EMAIL_HOST_USER]
send_mail(subject, message, emailFrom, emailTo, fail_silently=True)
context = locals()
template = "contact.html"
return render(request,template,context)
When I clicked submit button, I only received Review blocked sign-in attempt - google email.
So I have set my email account as Allow less secure apps: OFF.
Then hit the submit button again, I haven't received any email without any exception. As if sending email functionality working - browser loading for a little while.
I'm not sure why I couldn't receive email.
When I change fail_silently = False, I get a error like this.
SMTPAuthenticationError at /contact/
(534, '5.7.14 https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtS\n5.7.14 Mr_jh-DUic292PQTLx5X6kZmxxN8WFLelRksUwF0nHxSUPVpU_fX3m7ds3VOoUuTxL9Gya\n5.7.14 bqnAiUAIf2Er2n31EXEHIOpy2Kqn9cFH-PsIJSx1GBn_SxygkjHWgZ9KWc9cxIAKTGQtru\n5.7.14 O3QBqKb6vCyVHCiN8wUY6jAVRdoRg9aK9BL5GTo6QKUomIilah549hrwMgvMcYrrKCLMGI\n5.7.14 YuEWvMHHPdW6TXkBB75UP2wxRZ9fI> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 u2sm3991912edl.71 - gsmtp')
How can I handle it.