Got a strange error in my django app when trying to send an email from a contact form.
In DEBUG got a unicode error when submitting my contact form.
After looking at the traceback, the string that caused the unicode error was the DNS_NAME in the function CachedDnsName() in utils.py
The function returned my laptop's name, which is 'Portátil-HP'
I get the unicode error, but why is it happening?
settings.py
# Email setup
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypass'
EMAIL_PORT = 587
views.py
class Contactos(FormView):
#staticmethod
def get(request):
return render(request, 'site/contactos.html', {'form': Formulario()})
def post(self, request):
form = Formulario(request.POST or None)
if form.is_valid():
# All validation rules pass
# Process the data in form.cleaned_data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
send_mail(name, message, EMAIL_HOST_USER, [EMAIL_HOST_USER], fail_silently=False)
return render(request, 'site/contactos.html', {'form': Formulario()})
else:
return render(request, 'site/contactos.html', {'form': Formulario()})
The DNS_NAME should be in ascii (like a domain name), your á is likely breaking it.
As far as I'm aware there's no way to set the DNS_NAME manually (see this ticket)
The only solution might be to change the name of your laptop to something with simpler characters.
Try setting these as well:
EMAIL_FROM = 'emailtosentfrom#gmail.com'
SERVER_EMAIL = 'emailtosenterrorsfrom#gmail.com'
Related
I'm trying to put send a random 6 digit otp through email .Below code work for django 4.0 but not working in 3.2 ,
I'm not getting any error but when i createsuperuser in django 4.0 setup email send work but not the case in django 3.2
views.py
#receiver(post_save, sender=CustomUser)
def send_email_otp(sender, instance, created, **kwargs):
if created:
try:
subject = "Your email needs to be verified to use this site"
message = f'Hi, Dear {instance.name} use this following OTP to Get verified your email : OTP({instance.otpForEmail})/'
email_from = settings.EMAIL_HOST_USER
recipient_list = [instance.email]
send_mail(subject, message, email_from, recipient_list)
print(f"Email Sent to {instance.email}")
except Exception as e:
print(e)
print("Something Wrong at send_email_otp")
signals.py
from django.db.models.signals import pre_save
from .models import CustomUser
def updateUser(sender, instance, **kwargs):
user = instance
if user.email != '':
user.name = user.email
pre_save.connect(updateUser, sender=CustomUser)
I'm not sure what can be the problem,please help me to identify and fix .
Edit:
my email backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my#gmail.com' #Allow Secure connections is enabled
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
after saving my variables in views.py that I have forwarded, can I send them as mail while saving the same fields? My mail sending codes are below but I didn't know how to do it.
def gcreate(request):
if request.method == 'POST':
gmember = gunluk(
adsoyad=request.POST['adsoyad'],
adsoyad2=request.POST['adsoyad2'],
vardiya=request.POST['vardiya'],
aciklama=request.POST['aciklama'],
incident=request.POST['incident'],
alinanaksiyon=request.POST['alinanaksiyon'],
ulasilmayanekip=request.POST['ulasilmayanekip'],
ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],)
try:
gmember.full_clean()
except ValidationError as e:
pass
send_mail(
'test',
'testmessage',
'xx#xx.com',
['xx#xx.com'],
fail_silently=False
)
gmember.save()
messages.success(request, 'Ekleme İşlemi Başarılı!')
return redirect('/gunlukistakibi')
else:
return render(request, 'gcreate.html')
Did you check the Gmail less secure apps settings? Turn on 'less secure app access'.
from django.core.mail import send_mail
from django.conf import settings
def gcreate(request):
if request.method == 'POST':
gmember = gunluk(
adsoyad=request.POST['adsoyad'],
adsoyad2=request.POST['adsoyad2'],
vardiya=request.POST['vardiya'],
aciklama=request.POST['aciklama'],
incident=request.POST['incident'],
alinanaksiyon=request.POST['alinanaksiyon'],
ulasilmayanekip=request.POST['ulasilmayanekip'],
ulasilmayanbilgisi=request.POST['ulasilmayanbilgisi'],)
try:
gmember.full_clean()
except ValidationError as e:
pass
send_mail(
'Subject',
'Message.',
settings.EMAIL_HOST_USER,
['to#example.com'],
)
gmember.save()
messages.success(request, 'Ekleme İşlemi Başarılı!')
return redirect('/gunlukistakibi')
else:
return render(request, 'gcreate.html')
In settings.py put the following
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com' # else your smtp provider and Less Secure App should be allowed
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your email address'
EMAIL_HOST_PASSWORD = 'your email address password'
There are quite a few youtube or instructions online but I could not find anything to apply this to blog/create. What I mean by that, I would like to have email to be sent automatically to the guy who create a new post.
Here is the blog/views.py below;
from django.core.mail import send_mail
class PostCreate(LoginRequiredMixin, CreateView):
model = Post
fields = [
'title', 'content', 'head_image', 'category', 'tags'
]
def form_valid(self, form):
current_user = self.request.user
if current_user.is_authenticated:
form.instance.author = current_user
return super(type(self), self).form_valid(form)
else:
return redirect('/blog/')
I did setup settings.py like below:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'example#gmail.com' # my email address I put
EMAIL_HOST_PASSWORD = '****************' # the password I put
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
I have a project to do right now... I don't have much time to review and study again... I am such a beginner... looking forward to having some help from here
I have created the below django contact form for the contact page of my website. The problem with the form is that when a user fills and clicks the submit button, it show a success message but the email is not sent. i mean i don't receive message in my box
Can someone please check and tell me where I went wrong.
forms.py :
from django import forms
from django.forms import ModelForm
# contact form
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True )
contact_email = forms.EmailField(required=True )
title = forms.CharField(required=True)
content = forms.CharField(required=True )
views.py :
def contact(request):
Contact_Form = ContactForm
if request.method == 'POST':
form = Contact_Form(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name')
contact_email = request.POST.get('contact_email')
contact_content = request.POST.get('content')
title = request.POST.get('title')
template = loader.get_template('website_primary_html_pages/contact_form.txt')
context = {
'contact_name' : contact_name,
'contact_email' : contact_email,
'title' : title,
'contact_content' : contact_content,
}
content = template.render(context)
email = EmailMessage(
"Hey , There are new Message from blog",
content,
"Creative web" + '',
['contact#techpediaa.com'],
headers = { 'Reply To': contact_email }
)
email.send()
return redirect('Success')
return render(request, 'website_primary_html_pages/contact_us.html', {'form':Contact_Form })
#end contact form
settings.py :
#MY EMAIL SETTING
DEFAULT_FROM_EMAIL = 'contact#techpediaa.com'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
when user fills all fields it show message send success but i don't received any message why
i am using namecheap as a hosting
my new settings in settings.py :
#MY EMAIL SETTING
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'contact.techpediaa.com'
EMAIL_USE_TLS=False
EMAIL_PORT = 587
EMAIL_HOST_USER = 'contact#techpediaa.com'
EMAIL_HOST_PASSWORD = 'mypass'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Yes you can use this for Cpanel.
The processes will be the same for Cpanel as google. You will need to create a app password in the Cpanel
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'your_mail.your_domain_of_Cpanel'
EMAIL_USE_TLS=True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'email'
EMAIL_HOST_PASSWORD = 'app_password'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Try it now
If EMAIL_USE_TLS is getting any kind error then edit it False
You don't get an email in the inbox, because you're using django.core.mail.backends.console.EmailBackend - as you can see it will just output email in the console. Do you see it there?
SMTP Backend is what you need.
I need to send an email after user submits a form on my page (this is still in development, but it'll be in production soon).
I've read this other answer but after my form is submitted I'm not reciving any email (I've used my personal email as the sender and the receiver, for testing).
What I need to modify?
PLUS: How to send images on emails? Any tutorial on this? I need to send professional emails after form submition.
settings.py
EMAIL_HOST = 'smtp.gmail.com' # since you are using a gmail account
EMAIL_PORT = 587 # Gmail SMTP port for TLS
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'oma.oma#gmail.com' #Not my actual email
EMAIL_HOST_PASSWORD = 'MyPassword' #Not my actual password
views.py:
# here we are going to use CreateView to save the Third step ModelForm
class StepThreeView(CreateView):
form_class = StepThreeForm
template_name = 'main_app/step-three.html'
success_url = '/'
def form_valid(self, form):
form.instance.tamanios = self.request.session.get('tamanios') # get tamanios from session
form.instance.cantidades = self.request.session.get('cantidades') # get cantidades from session
del self.request.session['cantidades'] # delete cantidades value from session
del self.request.session['tamanios'] # delete tamanios value from session
self.request.session.modified = True
return super(StepThreeView, self).form_valid(form)
form.py:
from django.core.mail import send_mail
class StepThreeForm(forms.ModelForm):
instrucciones = forms.CharField(widget=forms.Textarea)
class Meta:
model = TamaniosCantidades
fields = ('imagenes', 'instrucciones')
def __init__(self, *args, **kwargs):
super(StepThreeForm, self).__init__(*args, **kwargs)
self.fields['instrucciones'].required = False
def send_email(self):
send_mail('Django Test', 'My message', 'oma.oma#gmail.com',
['oma.oma#gmail.com'], fail_silently=False)
You can override the save method like this in your Last Form:
class StepThreeForm(forms.ModelForm):
def save(self, commit=True):
instance = super(StepThreeForm, self).save(commit=commit)
self.send_email()
return instance
def send_email(self):
image = self.cleaned_data.get('imagenes', None)
msg = EmailMessage(
'Hello',
'Body goes here',
'from#example.com',
['to1#example.com', 'to2#example.com'],
headers={'Message-ID': 'foo'},
)
msg.content_subtype = "html"
if image:
mime_image = MIMEImage(image.read())
mime_image.add_header('Content-ID', '<image>')
msg.attach(mime_image)
msg.send()
You can check this SO Answer for more details on how to send image from Django