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")
Related
I am trying to send a password reset email to users, via an App we are developping with Django.
When trying the App locally, the user can select to reset a pwd if forgotten , input his email into a field and submit, in order to receive an email. The sender email is a business email address.
Checking into Sendgrid, I can see the activity log that the email has been processed and delivered. So it seems working.
However, when trying to do the same passing via Github, Azure, on https://XXXXXX.azurewebsites.net/en/password_reset/, I get the following :
SMTPSenderRefused at /en/password_reset/
(550, b'Unauthenticated senders not allowed', 'nicolas#XXXXX.com')
in the log I get the following as well:
raise SMTPSenderRefused(code, resp, from_addr)
Is there something I am missing with Azure, another key to include. I read through many similar issues, but could not find a suitable response to my problem. The fact Sendgrid works locally but not with Azure make me think I am missing a connection at that level. Otherwise, All other aspects of the App works when hosting it on Azure..
Below are the codes I am using:
in settings.py
import os
ALLOWED_HOSTS = ['XXXXXX.azurewebsites.net']
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' #Exactly that
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'nicolas#XXXXX.com'
in views :
from django.core import mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
def send_password_reset_email(request):
subject = 'email reset'
html_message = render_to_string('password_reset_email.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'nicolas#XXXXX.com'
form = (request.POST)
if form.is_valid():
data = form.cleaned_data
to=data.get("email")
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message,fail_silently=False)
in url.py:
urlpatterns=[
url('', views.send_password_reset_email)
]
merci
Nicolas
This is solved: If SendGrid works locally, but not on Azure:
In Azure, select ‘configuration', 'Application settings', 'new application settings' and then, as per below, using the correct API name made it work.
In SendGrid, I had named my API key ‘test’, and thought in Azure I should name it the same. However, I should have named it the same as in my code:
SENDGRID_API_KEY
Not obvious at first.
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")
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.
I am trying to build a online book store and I am trying to send an verification email to new signed users, but for some reason Email is not getting sent, I also tried to use app specific password in gmail.
A help will be greatly appreciated.
Here is my Email code in settings.py
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST='smtp.gmail.com'
EMAIL_HOST_USER='kshitu.rangari#gmail.com'
EMAIL_HOST_PASSWORD='jgpcjiajvklxraof'
EMAIL_PORT=587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'books#pickabook.com'
Code in my Views.py
from .models import Book
def index (request):
return render (request,'template.html')
def store (request):
return render (request, 'store.html' )
def store (request):
count = Book.objects.all().count()
context = {
'count':count,
}
return render (request,'store.html',context)
As you already have the settings for email ready and to test whether emails are being sent, do the following
In settings.py make
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Run interactive mode,
python manage.py shell
Import the EmailMessage module,
from django.core.mail import EmailMessage
Send the email,
email = EmailMessage('Subject', 'Body', to=['kshitu.rangari#gmail.com'])
email.send()
If the above works successfully then your gmail account is configured to send emails.
For Gmail specifically, you might need to toggle the "enable less secure apps" function within your Google account.
https://support.google.com/accounts/answer/6010255?hl=en
I need to always send the same file attached, but my signal is sending the full path of my server with my file.
e.g
/home/user/Sites/path_my_project/static/downloads/file.pdf
On my signal I get the file like this:
file_annex = ('path_my_file / myfile.pdf')
and sending the signal as follows:
EmailMessage message = (
to = str (to),
subject = subject,
template = template,
context = context,
reply_to = _from,
attachments = file_annex
)
this works, but sends with of full path,i not understand why.
I want only send the file.
According to the docs attachments must be: either email.MIMEBase.MIMEBase instances, or (filename, content, mimetype) triples.
So you could try something like:
file_annex = ('myfile.pdf', open('path/to/myfile.pdf').read(), 'application/pdf')
Then you must pass file_annex as a single item in a list:
message = EmailMessage(
...
attachments = [file_annex],
...
)
I prefer to use EmailMultiAlternatives to send emails with Django, it's easier for me, if you want to try it, just do:
from django.core.mail import EmailMultiAlternatives
subject = subject
from_email = 'from#example.com'
to = str(to)
text_content = 'This is an important message.' # This is text message
html_content = template # This is HTML message
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.attach_file('path_my_file / myfile.pdf')
msg.send()
Don't forget the brackets [ ] around to because this allways have to be a list, even it's only 1 e-mail address (it could be more)
There is text_content and html_content in case the receiver can't render html email
And you need in your settings.py your e-mail configuration:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'any_mail#gmail.com'
EMAIL_HOST_PASSWORD = 'email_pass'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
This configuration is good to send mails FROM gmail, if you use other email service, maybe you need to change some values.