TimeoutError when trying to send email in django - django

enter image description here
Hello i am getting TimeoutError while trying to send mail through django .
the error shows as:A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
def mail_send_view(request, id):
subject = 'Subject'
message = 'message'
send_mail(subject, message, 'kumar943954#gmail.com',
['aditya9090400#gmail.com'],fail_silently=False)
return render(request, 'blog/sharebymail.html', {'form': form, 'post': post, 'sent': sent})

That is more than likely coming from an issue with your email provider. Does your code works on your machine using the email/#console-backend ?
On settings.py, set EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' and try sending an email using your code. If the email display on console, it's an issue with your provider, and so your hosting platform.
Most hosting platform do not provide a default smtp value, you then need to find one and setup your env properly using smtp-backend:
host: EMAIL_HOST
port: EMAIL_PORT
username: EMAIL_HOST_USER
password: EMAIL_HOST_PASSWORD
use_tls: EMAIL_USE_TLS
use_ssl: EMAIL_USE_SSL
timeout: EMAIL_TIMEOUT
ssl_keyfile: EMAIL_SSL_KEYFILE
ssl_certfile: EMAIL_SSL_CERTFILE

Related

SMTPServerDisconnected when sending email from a Django App on Heroku with Mailgun

I'm attempting to send email from a very simple Django app. The app is hosted on Heroku, and I have the Mailgun add-on installed. However, whenever I attempt to actually send an email using Mailgun, I get a SMTPServerDisconnected error, with the message Connection unexpectedly closed.
I've gone through almost every tutorial that I can find on the subject, and have still had no luck. My settings.py is exactly as described in the Heroku Mailgun documentation:
EMAIL_USE_TLS = True
EMAIL_HOST = os.environ.get('MAILGUN_SMTP_SERVER')
EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', '')
EMAIL_HOST_USER = os.environ.get('MAILGUN_SMTP_LOGIN', '')
EMAIL_HOST_PASSWORD = os.environ.get('MAILGUN_SMTP_PASSWORD', '')
The os environment variables referenced are managed by Heroku. When I've searched for similar problems, every other question has been using Port 465, however, my port is on 587, which shouldn't have this issue as far as I know.
Currently, I'm using the sandbox domain provided by Mailgun just to attempt to send a test email to a verified recipient email. The following code is used in my views.py to actually send the email, using the django django.core.mail.send_mail() function.
subject = "Thank you for RSVP-ing!"
message = f'Hello World!'
email_from = "mailgun#blannholley.com"
recipient_list = [request.POST.get('email'), ]
send_mail(subject, message, email_from, recipient_list, fail_silently=False)
Any help would be greatly appreciated, as this is my first time attempting to send email over SMTP, so I'm very lost here and feel like I've tried everything.

Django is not sending e-mails

guys!
I have an issue with my Django project.
About project:
Django version: 3.0.7
Django hosting provider: Digitalocean
E-mail hosting provider: Beget.com
OS: Ubuntu 18.04.6
Here is my settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.beget.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'my#email.com'
EMAIL_HOST_PASSWORD = 'MyVerySecretPassword'
DEFAULT_FROM_EMAIL='my#email.com'
Here is my views.py
from django.core.mail import send_mail
def register(request):
if request.method == 'POST':
form = UserRegistrationForm(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 = 'Please, activate your account by clicking the link below.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL, [to_email])
What I have tried to solve my problem:
Using gmail account (yes, with anabled 'Allow less secure apps')
Sending via Django shell (nope, it returns code '1', the mailbox is as empty as my ideas:( )
I have opened 587 and 465 ports in ufw
I tried to write and run simple python smtp script to send e-mail via Django shell (spoiler: it worked perfectly on my server via shell), but when I tried to implement this code into my Django code, it failed just like Django send_mail() function:
here is the code:
import smtplib
def send_email(user, pwd, recipient, subject, body):
FROM = user
TO = recipient if isinstance(recipient, list) else [recipient]
SUBJECT = subject
TEXT = body
message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
print(message)
try:
server_ssl = smtplib.SMTP_SSL("smtp.beget.com", 465)
server_ssl.ehlo()
server_ssl.login(user, pwd)
server_ssl.sendmail(FROM, TO, message)
server_ssl.close()
print('successfully sent the mail')
except:
print("failed to send mail")
usn='sender#email.com'
pwd='MyVerySecretPassword'
rc=['reciever#email.com']
subj='HoHoHo'
body='Hello, world'
send_email(usn,pwd,rc,subj,body)
I checked all the variables (rendered them on the screen) which I tried to send via e-mail, all of them are correct.
Sorry, I am not interested in third party projects like Sendgrid. I just want to understand what I am doing wrong.
Hope someone could help me to find the bug. Thank you very much!
I have found the solution. Thank to Solarissmoke for answering to my question.
The real thing was in fact that my hosting provider blocked outgoing traffic. So the best solution is to user third-party mail delivery provider like Google or Sendinblue. After I changed my settings, everything worked.
Hope my post could help anyone.

Django contact form: email not sending

I'm currently building a contact form for my website in Django.
The only problem is that the email is not being sent when the form is submitted.
This is the code:
settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "c******o#gmail.com"
EMAIL_HOST_PASSWORD = '****'
EMAIL_PORT = '587'
views.py:
sender_name = form.cleaned_data['nome_completo']
sender_email = form.cleaned_data['email']
message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['messaggio'])
send_mail('New Enquiry', message, sender_email, ['c******o#gmail.com'])
My thought:
Since I'm in a virtualenv, when I submit the form, the terminal displays that it was successfully submitted, and gets me back the code right, maybe the email is not sent because of that, or maybe because I'm using a gmail account? Thanks!
Since you are using an SMTP server, why not use the following backend:
django.core.mail.backends.smtp.EmailBackend
Also, if you are using Gmail, make sure of the following:
Two-Factor authentication is enabled on account
You are using an app password.
You can find these on the security tab on your google account page:
https://myaccount.google.com/security
So the issue is with EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
This outputs emails to your console for debugging instead of actually sending emails. (See https://docs.djangoproject.com/en/3.1/topics/email/#console-backend)
Don't set EMAIL_BACKEND to anything for production as it defaults to django.core.mail.backends.smtp.EmailBackend. Then your EMAIL_HOST settings will take effect and the email should be sent out.

Could not send email in django rest framework

I am developing password reset part of the project. I am using django_rest_passwordreset to get the password reset. I am using mailjet smtp. I could not send the email to the user.
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'in-v3.mailjet.com'
# EMAIL_PORT = 465
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# EMAIL_USE_SSL = True
EMAIL_HOST_USER = '5e4329460b3c88f1d24d19c3e7374548aa213da%asasd1asd'
EMAIL_HOST_PASSWORD = 'a6c5ab2515d6ae761253a396453530ba$42asasdasdaasdasd'
If I change the EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' to the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' it is printing it to the console. I have no idea why it is not working.
the part of the code where I am trying to send an email.
#receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.firstname,
'email': reset_password_token.user.email,
'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key)
}
# just checking if it works
send_mail('Hello from something', 'hello there', 'abdukhashimov#yandex.ru',
[reset_password_token.user.email, ], fail_silently=False)
# render email text
email_html_message = render_to_string('user_reset_password.html', context)
email_plaintext_message = render_to_string(
'user_reset_password.txt', context)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {title}".format(title="Some website title"),
# message:
email_plaintext_message,
# from:
"noreply#somehost.local",
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
I came up with a different solution. I used the google smtp service. I have followed the steps from this kinsta.com - steps to setup up google smtp.
Step1: The very first thing you will need to do is ensure that you have 2-step verification enabled on your primary Gmail account. Important: If you don’t do this you will get an invalid password error further below when trying to authenticate your email address. So first go and enable 2-step verification.
Step2: Next, you will need to generate an App password. You then use the app password in place of your personal Gmail password further below. This is the only way this process will work.
Step3: Now back in Gmail, go to settings, and can click on “Accounts and Import.” Then click on “Add another email address you own.”. Basically to the gmail and sign in with your account and go to the settings.
Step4: Enter your additional business name and business email that is on the custom domain.
(Extra Info). I usually use yandex mail and added it then it generated the followings.
Step5: It will then send an email confirmation code to the email you just added. You will need to click the link in the email to confirm it or manually enter the code (this proves that you are in fact the owner of the additional email account). And that’s it!
From my experience, you might need to tweak some settings from google if it did not work for you. For example, I read from other source, you might need to allow less secure apps from google. I have not done it as I was using yandex mail, I guess.
In case if you are not sure what to put in settings.py
EMAIL_HOST = 'smtp.yandex.ru' # in my case
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'added account'
EMAIL_HOST_PASSWORD = 'your password'
Credits to kinsta.com

SMTPAuthenticationError Django

I was trying to send a verification email at my program, when I use gmail it works and send the verification email but now im trying to use my own mail server and it started to raise this error
SMTPAuthenticationError at /accounts/register/
(535, '5.7.8 Error: authentication failed:')
any idea why?
# EMAIL SETTINGS
EMAIL_HOST = "smtp.xxxx.xxx"
EMAIL_PORT = "25"
EMAIL_HOST_USER = "no-reply#xxxxx.net"
EMAIL_HOST_PASSWORD = "xxxxxxxxxxxxxxxxxx"
# Controls whether a secure connection is used.
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
Verify the username and password are exactly the same,
Do not give full e-Mail id if in case your smtp accepts just the username without domain
e.g.
e-Mail id : username#abc.com
in settings file, just give username when your smtp accepts it.