Send Email: user.email_user vs send_mail - django

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.

Related

(421, b'Service not available')

I have a simple method (send_activation_email) called from a view which handles user registration by extending default django user auth. It sends an activation email. Now I get the error:
Please help me out guys
Exception Type: SMTPConnectError
Exception Value:
(421, b'Service not available')
The Method Implementation
def send_activation_email(user, request):
current_site = get_current_site(request)
subject = 'Activate your membership Account'
message = render_to_string('accounts/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),
})
html_message = get_template('accounts/account_activation_html_email.html').render({
'user': user,
'domain': current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
send_mail(subject=subject,
message=message,
from_email= None,
recipient_list=[user.email],
html_message= html_message
#,fail_silently=False
)
Email Configuration in Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'asoliu34#gmail.com'
EMAIL_HOST_PASSWORD = 'syxkgrfbczefd' #past the key or password app here
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'default from email'.
Call the function in view
send_verification_email(request, user)
Template
{% autoescape off %}
Hi {{user.first_name}},
Please click on below link to verify your email
http://{{domain}}{% url 'activate' uidb64=uid token=token %}
{% endautoescape %}.

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'

how to send email in django

my settings in settings.py but not sending any mails to gmail account.
can u please expalin me how to send confirm mail to mailenter code here
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 587
I am getting success message in cmd but not sending email to my id
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
current_site = get_current_site(request)
print(current_site)
subject = 'Activate Your MySite 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),
})
from_email =settings.EMAIL_HOST_USER
print(from_email,"email here")
# to_email = [from_email,'sridharadhi50#gmail.com']
to_email = form.cleaned_data.get('email')
email = EmailMessage(
subject, message, to=[to_email]
)
email.send()
# user.email_user(subject, message)
return redirect('account_activation_sent')enter code here
In your python file
def get_email_connection():
use_tls = True
use_ssl = False
fail_silently=False
connection = get_connection(host=config.email_host,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASSWORD,
use_tls=use_tls,
use_ssl=use_ssl,
fail_silently=fail_silently)
return connection
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.save()
connection=get_email_connection()
current_site = get_current_site(request)
print(current_site)
subject = 'Activate Your MySite 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),
})
from_email =settings.EMAIL_HOST_USER
print(from_email,"email here")
# to_email = [from_email,'sridharadhi50#gmail.com']
to_email = form.cleaned_data.get('email')
email = EmailMessage(
subject, message,settings.EMAIL_HOST_USER, [to_email],connection=connection
)
email.send()
# user.email_user(subject, message)
return redirect('account_activation_sent')enter code here
You should give EMAIL_BACKEND
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'mail#gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
its work fine.

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