Django smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. ...) - python

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.

Related

SMTPSenderRefused at /Contact/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0

I want the users of my website after the login with gmail account using the google api to send to the account1#gmail.com email after entring the name and the email address and the message in the contact.html but i get this error despite i have activated the 2 factor authentication for the account1#gmail.com and create a password for my website .
this is my function contact in my views.py:
def contact(request):
if request.method=='POST':
message_name=request.POST['message-name']
message_email=request.user.email
message=request.POST['message']
print(message_email)
send_mail(
message_name,
message,
message_email,
['account1#gmail.com'],
fail_silently=False
)
return render(request,'store/Contact.html',{'message_name':message_name})
else:
return render(request,'store/Contact.html',{}
and this the settings.py:
EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_PASSWORD='password_of_the_app'
EMAIL_USE_TLS=True
EMAIL_USE_SSL=False
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID= 14
LOGIN_REDIRECT_URL= '/'
but when i add the EMAIL_HOST_USER='account1#gmail.com' i can send the email from the account1#gmail.com to account1#]gmail.com but not from the email feild that exist in my template.
really any help is appreciated
Try this:
Go to your google account.
Go to security.
Turn on Less Secure App Access.
Add this in your settings.py
EMAIL_HOST_USER = 'your email'
EMAIL_HOST_PASSWORD = 'your password'

Django does not send emails via smtp

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

django email not being sent : ConnectionRefusedError WinError 10061

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'

In Django1.10, sending email functionality not working without any exception

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.

Error: SMTPRecipientsRefused 553, '5.7.1 #while working on contact form in django

im trying to make a contact form in django 1.3, python 2.6.
Whats the reason of following error?
error:
SMTPRecipientsRefused at /contact/
{'test#test.megiteam.pl': (553, '5.7.1 <randomacc#hotmail.com>: Sender address
rejected: not owned by user test#test.megiteam.pl')}
my settings.py:
EMAIL_HOST = 'test.megiteam.pl'
EMAIL_HOST_USER = 'test#test.megiteam.pl'
EMAIL_HOST_PASSWORD = '###'
DEFAULT_FROM_EMAIL = 'test#test.megiteam.pl'
SERVER_EMAIL = 'test#test.megiteam.pl'
EMAIL_USE_TLS = True
edit: If any1 else was following djangobook, this is the part causing it:
send_mail(
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply#example.com'), #get rid of 'email'
['siteowner#example.com'],
The explanation is in the error message. Your email host is rejecting the email because of the sender address randomacc#hotmail.com that you have taken from the contact form.
Instead, you should use your own email address as the sender address. You can use the reply_to option so that replies go to your user.
email = EmailMessage(
'Subject',
'Body goes here',
'test#test.megiteam.pl',
['to#example.com',],
reply_to='randomacc#hotmail.com',
)
email.send()
On Django 1.7 and earlier, there isn't a reply_to argument, but you can manually set a Reply-To header:
email = EmailMessage(
'Subject',
'Body goes here',
'test#test.megiteam.pl',
['to#example.com',],
headers = {'Reply-To': 'randomacc#hotmail.com'},
)
email.send()
Edit:
In the comments you asked how to include the sender's address in the message body. The message and from_email are just strings, so you can combine them however you want before you send the email.
Note that you shouldn't get the from_email argument from your cleaned_data. You know that the from_address should be test#test.megiteam.pl, so use that, or maybe import DEFAULT_FROM_EMAIL from your settings.
Note that if you create a message using EmailMessage as in my example above, and set the reply to header, then your email client should do the right thing when you hit the reply button. The example below uses send_mail to keep it similar to the code you linked to.
from django.conf import settings
...
if form.is_valid():
cd = form.cleaned_data
message = cd['message']
# construct the message body from the form's cleaned data
body = """\
from: %s
message: %s""" % (cd['email'], cd['message'])
send_mail(
cd['subject'],
body,
settings.DEFAULT_FROM_EMAIL, # use your email address, not the one from the form
['test#test.megiteam.pl'],
)

Categories