Django SMTP [Errno 111] Connection refused - python

I am trying to send email from a web app using django and a sendgrid SMTP server. It works fine locally but when I try to use it on pythonanywhere I get
error: [Errno 111] Connection refused
The code from the relevant view is
def contact(request):
if request.method == 'POST':
form = EmailForm(request.POST)
if form.is_valid():
mail = form.cleaned_data
send_mail(
'Automated Enquiry',
'A user is interested in part ' + mail['part'] + '.Their message: ' + mail['msg'],
mail['email'],
['myemail#gmail.com'],
fail_silently = False,
)
return render(request, 'manager/error.html', {'msg': "Thanks, we will be in touch as soon as possible"})
else:
part = request.GET.get('part', '')
form = EmailForm()
return render(request, 'manager/contact.html', {'form': form, 'part':part})
And in my setting.py:
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'myuser'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
It didn't work from the console either.
Any help would be greatly appreciated.

free users on PythonAnywhere have restricted Internet access to a whitelist of sites, and only the HTTP/HTTPS protocols are allowed, so you cannot make SMTP connections to sendgrid from a free account.
you can use gmail from a free account, and pythonanywhere have instructions here.
or you can switch to using the sandgrid HTTP api: https://sendgrid.com/docs/Integrate/Frameworks/django.html

Related

Django email backend and smtp configuration

I'm trying to use my Zoho account within my django project, in order to receive emails via contact forms.
I also followed this guide: https://www.zoho.com/mail/help/zoho-smtp.html
In the 'settings.py' file I wrote:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtppro.zoho.eu'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '<domain name email>'
EMAIL_HOST_PASSWORD = '<password>'
and in views.py:
def home(request):
allTemplates = AllTemplates.objects.all()
if request.method == 'POST':
form = forms.ContactForm(request.POST)
if form.is_valid():
body = {
'name': form.cleaned_data['name'],
'surname': form.cleaned_data['surname'],
'from_email': form.cleaned_data['from_email'],
'message': form.cleaned_data['message'],
}
mail_body = "\n".join(body.values())
try:
send_mail("Generic contact", mail_body, '<domain name email>',
['<domain name email>'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Ops, qualcosa è andato storto')
form = forms.ContactForm
context = {'form': form, 'allTemplates': allTemplates,
'allTemplates_length': len(allTemplates)}
return render(request, 'home.html', context)
N.B. in 'send_email' I entered my email address twice to test
I also tried to use ssl
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtppro.zoho.eu'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = '<domain name email>'
EMAIL_HOST_PASSWORD = '<password>'
but nothing, I don't receive any email.
Is there anyone who has already gone through it or who can direct me towards some document or guide to study?
Thank you very much in advance.
I use
EMAIL_PORT = 587
EMAIL_USE_TLS = True
my biggest pain was that all emails went to spam folder and I did not realize that for 2 hours.
test with local output to terminal:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
test with local mail server to make sure the email is correctly created:
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST='localhost'
EMAIL_PORT=1025
and start local test mail server parallel to runserver in terminal window:
python -m smtpd -n -c DebuggingServer localhost:1025

STARTTLS extension not supported by server in django

i am using gmail to do this, and i'm still at development. it just keeps throwing this error. yesterday it was working. sometimes it would also stop and show this error, but throughout today it haven't been working as expected
setting.py
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "testemail#gmail.com"
EMAIL_HOST_PASSWORD = "mypassword"
views.py
def mail_letter(request):
emails = NewsLetter.objects.all()
df = read_frame(emails, fieldnames=['email'])
mail_list = df['email'].values.tolist()
print(mail_list)
if request.method == "POST":
form = MailMessageForm(request.POST)
if form.is_valid:
form.save()
# Sending Messages
title = form.cleaned_data.get('title')
message = form.cleaned_data.get('message')
send_mail(
title,
message,
'',
mail_list,
fail_silently=False,
)
# Success Alert
messages.success(request, f"Messages sent successfully")
subscribed = True
return redirect('elements:mail_letter')
else:
form = MailMessageForm()
This was later fixed by connecting to a new network, my network connection was not good

How to use AWS Simple Email Service (SES) in Django?

I'm trying to use this library to integrate my Django project with AWS SES.
settings.py
EMAIL_BACKEND = 'django_ses.SESBackend'
AWS_ACCESS_KEY_ID = 'my_aws_access_key'
AWS_SECRET_ACCESS_KEY = 'my_aws_secret_access_key'
AWS_SES_REGION_NAME = 'us-west-2'
AWS_SES_REGION_ENDPOINT = 'email.us-west-2.amazonaws.com'
It throws the following error
SESAddressNotVerifiedError: 400 Email address is not verified.
<ErrorResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/">
<Error>
<Type>Sender</Type>
<Code>MessageRejected</Code>
<Message>Email address is not verified. The following identities failed the check in region US-WEST-2: jpark1320#gmail.com, webmaster#localhost</Message>
</Error>
<RequestId>0220c0a0-741b-11e8-a153-475b5dfc6545</RequestId>
</ErrorResponse>
I can't even guess why is wrong on my codes. But, one thing might be a problem is send_mail(). I'm using trying to send an email to a user for sign-up confirmation. I put the codes for sending email below.
SMTP settings
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my_google_email#gmail.com'
EMAIL_HOST_PASSWORD = 'my_google_email_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'My Team Name <noreply#gmail.com>'
Update
views.py
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
# Create a user object to set email to be username before passing it to db
user = form.save(commit=False)
user.is_active = False
user.email = form.cleaned_data['username']
user.save()
current_site = get_current_site(request)
mail_subject = "[Modvisor] Please verify your email address."
message = render_to_string('accounts/account_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
to_email = user.email
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return redirect('signup_confirm')
else:
form = SignupForm()
return render(request, 'accounts/register.html', {'form': form})
The relevant part of the error is "Email address is not verified". By default SES is in sandbox mode where it won't let you use From or To addresses that you have not previously verified. You need to verify the addresses in the SES console or open a support request to leave sandbox.
Verifying Email Addresses in Amazon SES
To verify an address go to the SES console. On the left side select Email Addresses and then click Verify New Email Address. You will need to have access to the email address so you can click the link that will be sent to it.
Moving Out of the Amazon SES Sandbox
To move out of the sandbox simply open a support request, describe your use case and wait a few days.

Django sending email with google SMTP

I have been trying to get emails working with my Django application and have not been able to. Ive been reading around on similar questions and still haven't been able to pin point my error.
My settings.py looks like :
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email#domain'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
MY code to send the email looks like :
def application(request):
if request.method == 'GET':
form = ApplyForm()
else:
form = ApplyForm(request.POST)
if (form.is_valid()):
try:
subject = 'Overland Application'
from_email = form.cleaned_data['useremail']
phone = form.cleaned_data['phone']
names = form.cleaned_data['names']
year = form.cleaned_data['year']
make = form.cleaned_data['make']
model = form.cleaned_data['model']
message = str(names) + '\n' + str(from_email) + '\n' + str(phone) + '\n' + str(year) + '\n' + str(make) + '\n' + str(model)
try:
send_mail(subject, message, settings.EMAIL_HOST_USER, ['email#domain.com'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
except:
pass
return render(request, "overland/apply.html", {'form': form})
Some additional information is that it seems to be accessing my email account as I did receive an email from google saying there was suspicious access on my account from the location of the server.
I also pinged the smtp server from the live server to make sure that it was communicating.
I am not sure if it is a small syntax error on my part somewhere or I am using the django mail function incorrectly because locally it seemed to work and would redirect to my thanks page, but when I do this live it seems to just reload the page and not send anything.
Thanks in advance for any information.
This was an issue with gmail itself. Anybody running into this issue should first try going to security settings and allowing access to less secure apps. if that doesn't work try visiting https://accounts.google.com/DisplayUnlockCaptcha and then use your application to send the email again.

How to send django email via proxy with authentication

I am trying to send an email from a work PC that is behind a proxy.
In settings.py my code looks like this:
#email setup
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'username#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
In views.py:
from django.core.mail import send_mail
def home(request):
context = RequestContext(request)
send_mail('test email', 'hello world', 'sender#gmail.com', ['receiver#email.com'], fail_silently=False)
return render_to_response('project/home.html', context)
This gives the error:
[Errno 10061] No connection could be made because the target machine actively refused it
How can I implement authentication with the proxy?

Categories

Resources