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

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.

Related

Django is not sending email to admins on error 500 (but email settings do work with send_mail!)

I know, there are plenty of similar questions about this, but none of them helped. When I set the EMAIL_BACKEND to django.core.mail.backends.console.EmailBackend, I do see the email when I trigger a 500. When I set EMAIL_BACKEND to django.core.mail.backends.smtp.EmailBackend, I don't receive the email.. but email manually sent using the send_mail function gets delivered just fine, so the email settings do work. I just don't understand this.
DEBUG = False
EMAIL_BACKEND = env("EMAIL_BACKEND")
EMAIL_HOST = "smtp.sendgrid.net"
EMAIL_HOST_USER = "apikey"
EMAIL_HOST_PASSWORD = env("SENDGRID_API_KEY")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = "{my email}"
ADMINS = [
("Kevin Renskers", "{my email}"),
]
MANAGERS = ADMINS
I don't have any custom LOGGING set, and like I said with django.core.mail.backends.console.EmailBackend I do see the email in my console.
So how can it be that I can send email using send_mail, yet errors are not sent to me using the exact same email settings? I've looked in my sendgrid account activity, and yeah they are not sent at all.
Thank you #michjnich for the suggestion to try to call mail-admins manually. When I did I got a clear error:
The from address does not match a verified Sender Identity. Mail cannot be sent until this error is resolved.
Turns out I needed to change SERVER_EMAIL to another email address as configured in Sendgrid. The reason why my manual send_mail call worked fine, is because I gave it the correct from address there.

TimeoutError when trying to send email in 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

unable to send emails django-helpdesk

I am using django-helpdesk for ticketing system.
its working fine but i am not able to send emails. i am testing this on my localhost.
while i submit a ticket, its getting submitted properly but submitter is not getting any email for newly created ticket.
i added new queue and provided details like E-Mail Address, E-Mail Box Type, E-Mail Hostname, E-Mail Port, Use SSL for E-Mail=False, E-Mail Username, E-Mail Password, IMAP Folder, E-Mail Check Interval properly.
but emails not getting sent.
then i removed all off above from queue and added settings like
QUEUE_EMAIL_BOX_TYPE = IMAP
QUEUE_EMAIL_BOX_SSL = True
QUEUE_EMAIL_BOX_HOST = 'smtp.gmail.com'
QUEUE_EMAIL_BOX_USER = 'email'
QUEUE_EMAIL_BOX_PASSWORD = 'pwd'
but still its not working.
am i missing any settings? please help me out.
QUEUE_EMAIL_BOX settings are not for sending emails, but for receiving them. Configuration for sending emails goes into standard email settings from django.
If you're using SMTP backend (this is default), configuration should be:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_USE_SSL = True

Sending email on Heroku with the Django application Spirit

I'm setting up on a Django site the elegant forum application Spirit, but having just a bit of trouble getting it to send emails on the Heroku installation. This is undoubtedly because I'm a novice, a little unsteady about sending emails in Django, and not quite sure how to get the relevant debugging info. Some help would be much appreciated.
I installed the Postmark addon plus the Python-Postmark library. On the local installation, everything is perfectly fine: registration emails get delivered as they should when using the installation on my machine. The problem is only with the deployment version.
Also, when I enter
heroku run python
from django.config import settings
from django.core.mail import send_mail
send_mail('this is a test from the heroku server','body',settings.DEFAULT_FROM_EMAIL, ['the.robot#example.com'],fail_silently=False)
then the Postmark server sends the message and it is received. So... it seems like the Postmark installation, and the Django command send_mail at least sort of work on the Heroku server. It's just when I request e.g. a user activation message through the browser while using the forum application itself, on the Heroku server, that the mail is not sent.
Postmark is configured in the site's settings.py files like this.
EMAIL_BACKEND = 'postmark.django_backend.EmailBackend'
POSTMARK_API_KEY = os.environ['POSTMARK_API_KEY']
POSTMARK_SENDER = 'the.robot#example.com'
POSTMARK_TEST_MODE = False
POSTMARK_TRACK_OPENS = False
DEFAULT_FROM_EMAIL = POSTMARK_SENDER
SERVER_EMAIL = POSTMARK_SENDER
Here is the (slightly modified) code which is supposed to be sending the email.
def sender(request, subject, template_name, context, to):
site = 'example.com'
context.update({'site_name': 'example',
'domain': 'example.com',
'protocol': 'https' if request.is_secure() else 'http'})
message = render_to_string(template_name, context)
from_email = "the.robot#example.com"
if len(to) > 1:
kwargs = {'bcc': to, }
else:
kwargs = {'to': to, }
email = EmailMessage(subject, message, from_email, **kwargs)
def send_activation_email(request, user):
subject = _("User activation")
template_name = 'spirit/user/activation_email.html'
token = UserActivationTokenGenerator().generate(user)
context = {'user_id': user.pk, 'token': token}
sender(request, subject, template_name, context, [user.email, ])
I also tried using gmail as a mail server, as suggested in this answer, and the same problem recurred. That is, mail gets sent perfectly fine from the local installation, but is apparently not sent by the Heroku version. Likewise, the command send_mail then still works on Heroku.

The email_from in Django send_mail function not working [duplicate]

This question already has answers here:
How to change from-address when using gmail smtp server
(6 answers)
Closed 3 years ago.
I put a contact form in my site, and I have this in my settings.py
# Email settings
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = '****'
EMAIL_PORT = 587
And this in my views.py
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
subject = 'Email from ' + name
content = name + '\r\n' + email + '\r\n\r\n' + message
send_mail(subject, content, email, ['me#myemail.com'])
It all works correctly, i get the email with all the information, but, the email comes from myemail#gmail.com even though the from_email parameter has the email var with the senders email.
It doesn't work that way or i'm doing something wrong?
I wanted to get the email from the sender, so y can just reply to it, like i do in PHP.
Thank you.
Gmail will not let you spoof where the email came from.
per user iAn in a similar post
The short answer - you can't.
Google rewrites the From and Reply-To headers in messages you send via it's SMTP service to values which relate to your gmail account.
The SMTP feature of gmail isn't intended to be an open or relay service. If it allowed any values for the From header, it would significantly dilute Google's standing with spam services, as there would be no way to verify the credentials of the sender.
You need to consider alternatives. How are you planning to host your script/application/website when it's finished: virtually every hosting solutions (shared/vps/dedicated server) will come pre-configured with an email transfer solution: be it sendmail or postfix on *nix, or IIS on Windows.
If you are intent on using gmail then you could:
Setup a dedicated "myapp#gmail.com" account
If you own the domain you are supposedly sending from, use the free gmail for domains, and setup a "myapp#mydomain.com" account.