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.
Related
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
So I've been working on this blog website and I wanted to add a form so that users can contact the blog admin. However when they fill out the form and send email.. The email I receive is from myself and not from the user. Someone Please help me to fix it.
The form is working correctly and message-email does return the email that they enter.
e.g. lets say in my form I add a user email as example1#example.com
but when I recieve an email it's not coming from example1#example.com but from my host email myemail#gmail.com.
views.py:
def contact(request):
if request.method == 'POST':
message_name = request.POST['message-name']
message_email = request.POST['message-email']
message = request.POST['message']
#send mail
send_mail(
'message from ' + message_name + ' their email ' + message_email ,
message,
message_email,
['myemail#gmail.com'],
)
return render(request, 'blog/contact.html', {'message_name':message_name})
settings.py:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POST = 587
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_USE_TLS = True
This may have some useful information.
https://www.digitalocean.com/community/tutorials/how-to-use-google-s-smtp-server
Note: Google will automatically rewrite the From line of any email you
send via its SMTP server to the default email address associated with
the account if the one used is not on the Send mail as addresses list
in Gmail or G Suite settings. You can verify the list by going to the
Accounts and Import tab on the settings screen.
You need to be aware of this nuance because it affects the
presentation of your email, from the point of view of the recipient,
and it may also affect the Reply To setting of some programs.
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
I would like to enable people that visit my website to be able to send me an email to my yahoo mail. How can I do this? Now, I don't have a mail server (yet). Would it be necessary? The idea is for the person sending the email to fill in his email, subject and message, and then it would be posted to my yahoo email.
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = request.POST.get['subject']
email = request.POST.get['email']
message = request.POST.get['message']
if subject and email and message:
try:
send_mail(subject, message, email, ['my_email#yahoo.com'], fail_silently=False,)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
else:
return HttpResponse('Make sure to have all fields filled.')
return render(request,"mywebsit/contact.html", {'form':form})
The form renders ok, but when I press send it acts as if it has sent the message, but when I open my yahoo mail there's nothing new there.
I read it would be necessary to configure some things at settings.py, but, as far as I get it, it is meant to SEND, whereas what I want is to RECEIVE.
Inspite of that, I tried configuring it,
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.mail.yahoo.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'email#yahoo.com'
EMAIL_HOST_PASSWORD = 'yahoopassword'
DEFAULT_FROM_EMAIL = 'email#yahoo.com'
DEFAULT_TO_EMAIL = 'email#yahoo.com'
and then what I get is this error:
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
What should I do?
Looks like a networking issue, Are you hosting your website? Also the mail server depends on how much traffic your site is getting, if there is a lot then yeah it's a good idea but if not just having an HTML code that hyperlinks a new window to compose an email to your Yahoo account can do the trick too.
It should be request.post.get('Subject')
You are using [] bracket but it should be () bracket
I am having difficulties in configuring my settings.py so that I can send email from a webserver with any sender name
This is what I have done:
EMAIL_USE_TLS = True
EMAIL_HOST = 'mail.wservices.ch'
HOSTNAME = 'localhost'
DEFAULT_FROM_EMAIL = 'info#domain.com'
And sending email like this:
html_content = render_to_string('htmlmail.html', {})
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives('subject!',text_content,'info#domain.com',['to#domain.com'])
msg.attach_alternative(html_content, "text/html")
msg.send()
But I am getting:
{('to#domain.com': (554, '5.7.1 <to#domain.com>: Relay access denied')}
In one function, I have two msg.send() calls, BTW.
What am I doing wrong?
this is the answer webmaster when i asked how to send mails from webserver programmatically:
It is possible to send mails from E-Mail-Server "mail.wservices.ch".I suggest to
use the local installed Mail-Server. Hostname: localhost
There you can set any sender name, they just have to exist.
https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
Make sure first you have properly install django-sendmail
$ sudo apt-get install sendmail
in the settings.py :
from django.core.mail import send_mail
DEFAULT_FROM_EMAIL='webmaster#localhost'
SERVER_EMAIL='root#localhost'
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER=''
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 25 #587
EMAIL_USE_TLS = False
in views.py:
from project.apps.contact import ContactForm
def contactnote(request):
if request.method=='POST':
form =ContactForm(request.POST)
if form.is_valid():
topic=form.cleaned_data['topic']
message=form.cleaned_data['message']
sender=form.cleaned_data.get('sender','email_address')
send_mail(
topic,
message,
sender,
['myaddress#gmail.com'],fail_silently=False
)
#return HttpResponseRedirect(reverse('games.views.thanks', {},RequestContext(request)))
return render_to_response('contact/thanks.html', {},RequestContext(request)) #good for the reverse method
else:
form=ContactForm()
return render_to_response('contact.html',{'form':form},RequestContext(request))
contact.py:
from django import forms as forms
from django.forms import Form
TOPIC_CHOICES=(
('general', 'General enquiry'),
('Gamebling problem','Gamebling problem'),
('suggestion','Suggestion'),
)
class ContactForm(forms.Form):
topic=forms.ChoiceField(choices=TOPIC_CHOICES)
sender=forms.EmailField(required=False)
message=forms.CharField(widget=forms.Textarea)
#the widget here would specify a form with a comment that uses a larger Textarea widget, rather than the default TextInput widget.
def clean_message(self):
message=self.cleaned_data.get('message','')
num_words=len(message.split())
if num_words <4:
raise forms.ValidationError("Not enough words!")
return message
Try it , this is a whole working example apps, modify it
to be send to to mailserver like a reply when it got an mail, very simple to modify it