sending mail with drf django - django

i'm trying to send mail after signup from django drf:
settings.py:
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'
serializers.py:
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(email=validated_data['email'])
user.set_password(validated_data['password'])
user.save()
to_mail = user.email
send_mail('Subject here','Here is the message.','myemail#gmail.com',['to_mail',],fail_silently=False,)
return user
class Meta:
model = UserModel
fields = ( "id", "email", "password", )
im'm getting this error:
SMTPRecipientsRefused at /api/registration/
{'=?utf-8?q?to=5Fmail?=': (553, b'5.1.3 The recipient address <=?utf-8?q?to=5Fmail?=> is not a valid RFC-5321\n5.1.3 address. u2sm31792629pgc.19 - gsmtp')}
i'm even tried to send mail to different mail but i'm still gettings this error

Make sure to Enable IMAP and/or POP3. If you are getting the same error after enabling IMAP or POP3 try the code by removing email_backend.
#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'

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 email does not work and don't sent email

I am following this tutorial
the aim to verify email after users register to the system. here is the code.
serializers.py
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=68, min_length=6, write_only=True)
default_error_messages = {
'username': 'The username should only contain alphanumeric characters'}
class Meta:
model = User
fields = ['email', 'username', 'password']
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not username.isalnum():
raise serializers.ValidationError(
self.default_error_messages)
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
my view.py
class RegisterView(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('email-verify')
absurl = 'http://' + current_site + relativeLink + "?token=" + str(token)
email_body = 'Hi ' + user.username + \
' Use the link below to verify your email \n' + absurl
data = {
'email_body': email_body ,
'to_email': user.email ,
'email_subject' : 'Verify your email'
}
Util.send_email(data)
return Response(user_data , status=status.HTTP_201_CREATED)
my utils.py
class EmailThread(threading.Thread):
def __init__(self, email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
class Util:
#staticmethod
def send_email(data):
email = EmailMessage(
subject=data['email_subject'], body=data['email_body'] , to=[data['to_email']])
EmailThread(email).start()
and the settings.py
EMAIL_USE_TLS = True
EMAIL_HOSTS = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "talibdaryabi#gmail.com"
EMAIL_HOST_PASSWORD = "**********"
when I test the URL http://127.0.0.1:8000/auth/register/
by providing
{
"email":"talibacademic#gmail.com",
"username":"talibacademic",
"password":"aahg786ahg786"
}
I get the
{
"email": "talibacademic#gmail.com",
"username": "talibacademic"
}
which means the user was created but can't receive email.
can anyone help me with the issue, I also have allowed Less secure app access setting for talibdaryabi#gmail.com account.
In your settings.py, you need to define EMAIL_BACKEND,
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = youremail
EMAIL_HOST_PASSWORD = ****
EMAIL_USE_TLS = True
Note:
It's better to store your credentials in environment variables.

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

Sending email in django.

I have a page where people can submit an email. It works, but I receive all emails from it saying that they are from myself.
Here's the view:
def signup(request):
if request.method == 'POST': # If the form has been submitted...
form = SignUpForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
recipients = ['illuminatirebellion#gmail.com']
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = SignUpForm() # An unbound form
return render_to_response('signup.html', {'form': form,},context_instance=RequestContext(request))
And the settings:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'illuminatirebellion#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
MANAGERS = ADMINS
Your usage of send_mail() appears to be correct.
Assuming that Gmail is your SMTP vendor, it seems that Gmail does not support using custom From: email addresses.
Relevant:
Rails and Gmail SMTP, how to use a custom from address
How to change from-address when using gmail smtp server