not able to send email while user creation - django

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

Related

Django Create post and send mail

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'

contact form send email success but no message in my email box - django

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.

Email not being sent using Django send_mail()

settings.py:
EMAIL_HOST = 'smtp.mail.yahoo.com'
SMTP_PORT = 456
EMAIL_HOST_USER = 'my_email#yahoo.com'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_USE_SSL = True
the method:
def contact(*args,**kwargs):
contactform = ContactForm(request.POST, prefix='contactform')
send_mail(
'Contact from website by '+contactform.name,
contactform.message,
settings.EMAIL_HOST_USER,
['saxoya8501#emailhost99.com'],
fail_silently=False,
)
It does not send any email. In the logs I get:
"GET /?contactform-name=myname&contactform-email=aaaa%40gnm.com&contactform-message=aaaaaaaaaaaaaa HTTP/1.1" 200 20808
The form that I am using is this:
class ContactForm(forms.Form):
prefix = 'contactform'
name = forms.CharField(max_length=50)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea(attrs={'class':'materialize-textarea'}))
Any suggestions on how to get it to work?
This might be an issue because of your Gmail security. Give permission in your gmail account settings to allow unsecure apps

Django: send email on form submition

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

Django - sending emails (SMTPAuthenticationError)

I use:
from django.core.mail import send_mail
in my app. Yesterday my app normally sent emails without any errors. Today I get "SMTPAuthenticationError". Below is a part of my settings.py:
EMAIL_HOST = 'poczta.interia.pl'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'username'
EMAIL_ADRESS = 'email_adress'
EMAIL_HOST_PASSWORD = 'password'
This is my email function:
def send_activation_email(self):
subject = 'SUBJECT'
message = 'MESSAGE'
from_email = settings.EMAIL_ADRESS
to_email = self.email
send_mail(
subject,
message,
from_email,
[to_email],
fail_silently=False,
)
I don't have any idea what is going on. Yesterday it was fine, today not. Any ideas?