Django form send emails in console but not to my mailbox - django

I'm getting some practice using Django and now I'm stuck trying to get a contact form to work.
What I'm trying to do is: once the "Submit" button is clicked, I should receive the form data in an email arriving at the email address linked to my website. Instead what happens is: once I clicked on the "Submit" button, the page loads for some time and at the end I get a SMTPServerDisconnected error.
Can you tell me if I made a mistake in writing some logic or if it is a problem that I have to solve with my hosting service?
This is forms.py:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Your name', max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'name'}))
from_email = forms.EmailField(label='Your email', max_length=200, widget=forms.TextInput(
attrs={'class': 'form-control', 'id': 'email'}))
subject = forms.CharField(label='Enter a subject', max_length=200,
widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'subject'}))
message = forms.CharField(label='Write here your message', max_length=500,
widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'message'}))
This is view.py (I replaced each address with dummy addresses):
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
body = {
'first_name': form.cleaned_data['name'],
'email_from': form.cleaned_data['from_email'],
'message': form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(subject, message, 'example#example.com',
['mydomainemail#example.net'], fail_silently=True)
except BadHeaderError:
return HttpResponse('Invalid header found')
form = ContactForm()
return render(request, 'index.html', {'form': form})
And this is settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'mail.mydomain.net'
EMAIL_PORT = SmtpPort
EMAIL_HOST_USER = 'mydomainemail#example.net'
EMAIL_HOST_PASSWORD = 'my email password'
I tried to see if in the VS Code terminal the form works and that's why I replaced
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
with
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
and it works.
So I tried to replace the EMAIL_PORT with the IMAP PORT and POP3 PORT, but nothing happened.

One of the reason why that doesnt work is a lot of mail providers use two step authentication. for my case it was outlook that have the issue. i suggest creating a gmail account and add app password and use that email to send emails. here you can find how to use that.

Related

Send Email: user.email_user vs send_mail

I'm trying to send a email for users. In one situation it sends, but in other didn't send.
If I use 'email_user' it sends the email.
'user' is an autentificated user (built in with django).
About 'send_mail' I know after reading the documentation.
current_site = get_current_site(request)
subject = 'Activate Your Account'
message = render_to_string('account_activation_email.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
return redirect('account_activation_sent')
But when I want to use send_mail instead of email_user, it's not working. I want to understand what I do wrong.
send_mail(subject, message, email_from, recipient_list, fail_silently=False)
My settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = get_secret('EMAIL_HOST_USER')
EMAIL_HOST = get_secret('EMAIL_HOST')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = get_secret('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = get_secret('EMAIL_HOST_PASSWORD')
# Custom setting. To email
RECIPIENT_ADDRESS = ['None']
I understand what happened.
send_mail is working only with EMAIL_HOST which provided by gmail.
But when I want to send email to another email_service, then it's working with email_user. Thanks for all.

django sendgrid get error when sending email

I set up sendgrid as following and it works perfectly when I use send_mail to send a test message
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = '******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
Howerver when I implement it with an activation code in views.py for registration as bellow:
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save() #completed sign up
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
login(request, user)
# Create data in profile table for user
current_user = request.user
data=UserProfile()
data.user_id=current_user.id
data.image="images/users/user.png"
data.save()
current_site = get_current_site(request)
subject = 'Please Activate Your Account'
# load a template like get_template()
# and calls its render() method immediately.
message = render_to_string('user/activation_request.html', {
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
# method will generate a hash value with user related data
'token': account_activation_token.make_token(user),
})
user.email_user(subject, message)
return redirect('activation_sent')
# messages.success(request, 'Your account has been created!')
# return HttpResponseRedirect('/')
else:
messages.warning(request,form.errors)
return HttpResponseRedirect('/register')
form = SignUpForm()
#category = Category.objects.all()
context = {
'form': form,
}
return render(request, 'user/register.html', context)
It throws out this error:
SMTPDataError at /register
(550, b'The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved. Visit https://sendgrid.com/docs/for-developers/sending-email/sender-identity/ to see the Sender Identity requirements')
I have verified the sender and that's why It works with send_mail but it doesn't work with activation code.
Please someone have a look for me.
Thanks
It is missing sender email in following code:
user.email_user(subject, message)
It should be:
user.email_user(subject, message,"email#example.com")
Sendgrid requires to setup sender before you're able to send email.
Go to your sendgrid management page (https://app.sendgrid.com/settings/sender_auth) and create a sender. A sender must be verified.
Then django, you can set default email in settings.py
DEFAULT_FROM_EMAIL = <your sendgrid sender>

Why my django app can't send email to registered user?

I am trying to send user an email containing invitation/confirmation link.Command propmt is showing that email is being sent but user is not receiving any email.I am using my gmail account and also allows access by less secure apps on my account? What can be the possible errors?
Here is my settings file:-
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'someone#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
while my view uilizing it is as follows:-
#csrf_protect
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return JsonResponse({'success':True})
else:
form=SignupForm()
return JsonResponse({'errors': [(k, v[0]) for k, v in form.errors.items()]})
Strange enough that my console is showing the email but the targeted user did not receive that email.
The culprit is this line of your configuration:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
From django documentation on
console.EmailBackend:
Instead of sending out real emails the console backend just writes the
emails that would be sent to the standard output.
If you want to send out real emails choose a suitable backend. Since you seem to be attempting to use smtp you most likely want to use django's smtp.EmailBackend like this:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

smpt django on production server

I deploy my django project and my contact form stoped work. I tried some tips find on stack, but it doesn't works, help me plz.
Here my local settings:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
and my view:
def contact_form(request):
form = ContactForm(request.POST or None)
if form.is_valid():
message = form.cleaned_data.get('message')
email = form.cleaned_data.get('email')
subject = 'contact form'
from_email = email
to_email = (settings.EMAIL_HOST_USER,)
contact_message = '%s, from %s' %(message, from_email)
send_mail(subject, contact_message, from_email, to_email, fail_silently=False)
form = ContactForm()
request.session.set_expiry(10)
request.session['pause'] = True
return render(request, 'contact_form.html', {'form':form})
Now when I send message I have "Internal Server Error".
I contacted Baterson via Skype and solved this issue together. the production server didnot support smtp settings and there were some other bugs. So we fixed them all and finally decided to just use:
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
all is working now

Django Contact Form Mail Error

My form sends the email from the account listed in my settings.py fine, but in the message I only get the subject part of the form and the message part. There is no sender part within the email, so I can't tell who would be sending the email. Does anyone know how to fix this?
My forms.py
class ContactForm(forms.Form):
subject = forms.CharField(max_length=50)
message = forms.CharField()
sender = forms.EmailField()
My Views.py contact function
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
recipients = ['otheremail#gmail.com']
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/')
else:
form = ContactForm()
return render(request, "contact.html", {'form':form,})
My Settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
That code should work fine. I have implemented the same thing below and it works, but I had one issue with gmail that you might be having.
send_mail(Subject, Message, 'myemail#example.ca', To)
The issue was that in order to have the sender be the sender I assigned when using gmail in settings - the "sender" had to be in the approved senders list within your gmail account settings.
Hope that helps.
You will have to use the EMAIL_HOST_USER as the sender because you are going to send the mail from this user account.
Please import your settings in your views.py as mentioned below.
import settings
send_mail(subject, message, settings.EMAIL_HOST_USER, recipients)