I would like to enable people that visit my website to be able to send me an email to my yahoo mail. How can I do this? Now, I don't have a mail server (yet). Would it be necessary? The idea is for the person sending the email to fill in his email, subject and message, and then it would be posted to my yahoo email.
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = request.POST.get['subject']
email = request.POST.get['email']
message = request.POST.get['message']
if subject and email and message:
try:
send_mail(subject, message, email, ['my_email#yahoo.com'], fail_silently=False,)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
else:
return HttpResponse('Make sure to have all fields filled.')
return render(request,"mywebsit/contact.html", {'form':form})
The form renders ok, but when I press send it acts as if it has sent the message, but when I open my yahoo mail there's nothing new there.
I read it would be necessary to configure some things at settings.py, but, as far as I get it, it is meant to SEND, whereas what I want is to RECEIVE.
Inspite of that, I tried configuring it,
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.mail.yahoo.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = 'email#yahoo.com'
EMAIL_HOST_PASSWORD = 'yahoopassword'
DEFAULT_FROM_EMAIL = 'email#yahoo.com'
DEFAULT_TO_EMAIL = 'email#yahoo.com'
and then what I get is this error:
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
What should I do?
Looks like a networking issue, Are you hosting your website? Also the mail server depends on how much traffic your site is getting, if there is a lot then yeah it's a good idea but if not just having an HTML code that hyperlinks a new window to compose an email to your Yahoo account can do the trick too.
It should be request.post.get('Subject')
You are using [] bracket but it should be () bracket
Related
Settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com'
EMAIL_HOST_USER = config('SMTP_USER')
EMAIL_HOST_PASSWORD = config('SMTP_PW')
EMAIL_PORT = 587
VERIFIED_IDENTITY = config('VERIFIED_IDENTITY')
I have a verified email in my AWS SES and I am trying to send a message. I get a sent message everytime I use my contact form but no message actually gets sent.
if 'contactForm' in request.POST:
#print('Contact form')
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
contact_form.save()
email_subject = f'New contact {contact_form.cleaned_data["email"]}: {contact_form.cleaned_data["subject"]}'
email_message = contact_form.cleaned_data['message']
print(email_subject,email_message)
try:
send_mail(email_subject, email_message,settings.VERIFIED_IDENTITY,[settings.VERIFIED_IDENTITY])
except BadHeaderError:
print('bad')
In my opinion the issue might be related to DNS SPF record. See below the link related.
"A sender policy framework (SPF) record is a type of DNS TXT record that lists all the servers authorized to send emails from a particular domain."
https://www.cloudflare.com/learning/dns/dns-records/dns-spf-record/#:~:text=A%20sender%20policy%20framework%20(SPF,Domain%20Name%20System%20(DNS).
https://docs.aws.amazon.com/ses/latest/dg/send-email-authentication-spf.html
To set up SPF, you publish a TXT record to the DNS configuration for your domain. This record contains a list of the servers that you authorize to send email from your domain. When an email provider receives a message from your domain, it checks the DNS records for your domain to make sure that the email was sent from an authorized server.
Regards,
Ed.
So I've been working on this blog website and I wanted to add a form so that users can contact the blog admin. However when they fill out the form and send email.. The email I receive is from myself and not from the user. Someone Please help me to fix it.
The form is working correctly and message-email does return the email that they enter.
e.g. lets say in my form I add a user email as example1#example.com
but when I recieve an email it's not coming from example1#example.com but from my host email myemail#gmail.com.
views.py:
def contact(request):
if request.method == 'POST':
message_name = request.POST['message-name']
message_email = request.POST['message-email']
message = request.POST['message']
#send mail
send_mail(
'message from ' + message_name + ' their email ' + message_email ,
message,
message_email,
['myemail#gmail.com'],
)
return render(request, 'blog/contact.html', {'message_name':message_name})
settings.py:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POST = 587
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = '******'
EMAIL_USE_TLS = True
This may have some useful information.
https://www.digitalocean.com/community/tutorials/how-to-use-google-s-smtp-server
Note: Google will automatically rewrite the From line of any email you
send via its SMTP server to the default email address associated with
the account if the one used is not on the Send mail as addresses list
in Gmail or G Suite settings. You can verify the list by going to the
Accounts and Import tab on the settings screen.
You need to be aware of this nuance because it affects the
presentation of your email, from the point of view of the recipient,
and it may also affect the Reply To setting of some programs.
Hello I am trying to create password reset view in Django. I have set up the mail backend and urls and templates. Everything looks fine but when I try to send mail to reset password Django is sending multiple emails. For example 7 or 11 password reset email at the same time. How can I make it just one email for each time.
Thanks a lot
This is What I did:
setting.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = "my_email"
EMAIL_HOST_PASSWORD = "my_password"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
urls.py
path('password-reset/',
auth_views.PasswordResetView.as_view(template_name='accounts/password_reset.html'),
name='password_reset'),
path('password-reset/done/',
auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'),
name='password_reset_done'),
path('password-set-confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'),
name='password_reset_confirm'),
path('password-set-complete/',
auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'),
name='password_reset_complete'),
Also, I set the templates for each view.
IF this is still a problem... If you have multiple "test users" and you created them with the same email address that is probably causing your problme
It sometimes helps to check the Django source code itself, so always dive into that if you don't understand what's happening.
If you look at PasswordResetForm's save() method in django.contrib.auth.forms, you'll see that it loops through self.get_users(email) and then sends one (and only one) email for each user.
So the only way multiple emails can be sent is if there are multiple users with the same email.
I don't think their is any setting for the same you may be end up calling same URL multiple time might be a logic issue.
Try to use debug mode or with the help of print statements.
PasswordResetForm has get_users() method which returns all active usernames in an email. We can overwrite that method to return just 1 user which is passed to it. This way password reset email will be sent to only 1 user that we choose.
from django.contrib.auth.forms import PasswordResetForm
class MyPasswordResetFormSpecificUser(PasswordResetForm):
"""
Send password reset email to specific user and not all active
users in an email.
"""
user = None
def get_users(self, email):
"""
Instead of getting all users in an email,
just sent the user that we want to reset password for.
"""
return [self.user]
Then you can use this new form class into your views as shown below:
email = 'your email here'
form = MyPasswordResetFormSpecificUser({'email': email})
assert form.is_valid()
form.user = 'User object who needs password reset'
# use https only when running on GAE
form.save(
request=self.request,
use_https=False # True if you are deploying to https url
)
I have been trying to get emails working with my Django application and have not been able to. Ive been reading around on similar questions and still haven't been able to pin point my error.
My settings.py looks like :
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email#domain'
EMAIL_HOST_PASSWORD = 'pass'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
MY code to send the email looks like :
def application(request):
if request.method == 'GET':
form = ApplyForm()
else:
form = ApplyForm(request.POST)
if (form.is_valid()):
try:
subject = 'Overland Application'
from_email = form.cleaned_data['useremail']
phone = form.cleaned_data['phone']
names = form.cleaned_data['names']
year = form.cleaned_data['year']
make = form.cleaned_data['make']
model = form.cleaned_data['model']
message = str(names) + '\n' + str(from_email) + '\n' + str(phone) + '\n' + str(year) + '\n' + str(make) + '\n' + str(model)
try:
send_mail(subject, message, settings.EMAIL_HOST_USER, ['email#domain.com'], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('thanks')
except:
pass
return render(request, "overland/apply.html", {'form': form})
Some additional information is that it seems to be accessing my email account as I did receive an email from google saying there was suspicious access on my account from the location of the server.
I also pinged the smtp server from the live server to make sure that it was communicating.
I am not sure if it is a small syntax error on my part somewhere or I am using the django mail function incorrectly because locally it seemed to work and would redirect to my thanks page, but when I do this live it seems to just reload the page and not send anything.
Thanks in advance for any information.
This was an issue with gmail itself. Anybody running into this issue should first try going to security settings and allowing access to less secure apps. if that doesn't work try visiting https://accounts.google.com/DisplayUnlockCaptcha and then use your application to send the email again.
I am having difficulties in configuring my settings.py so that I can send email from a webserver with any sender name
This is what I have done:
EMAIL_USE_TLS = True
EMAIL_HOST = 'mail.wservices.ch'
HOSTNAME = 'localhost'
DEFAULT_FROM_EMAIL = 'info#domain.com'
And sending email like this:
html_content = render_to_string('htmlmail.html', {})
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives('subject!',text_content,'info#domain.com',['to#domain.com'])
msg.attach_alternative(html_content, "text/html")
msg.send()
But I am getting:
{('to#domain.com': (554, '5.7.1 <to#domain.com>: Relay access denied')}
In one function, I have two msg.send() calls, BTW.
What am I doing wrong?
this is the answer webmaster when i asked how to send mails from webserver programmatically:
It is possible to send mails from E-Mail-Server "mail.wservices.ch".I suggest to
use the local installed Mail-Server. Hostname: localhost
There you can set any sender name, they just have to exist.
https://docs.djangoproject.com/en/dev/ref/settings/#default-from-email
Make sure first you have properly install django-sendmail
$ sudo apt-get install sendmail
in the settings.py :
from django.core.mail import send_mail
DEFAULT_FROM_EMAIL='webmaster#localhost'
SERVER_EMAIL='root#localhost'
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER=''
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 25 #587
EMAIL_USE_TLS = False
in views.py:
from project.apps.contact import ContactForm
def contactnote(request):
if request.method=='POST':
form =ContactForm(request.POST)
if form.is_valid():
topic=form.cleaned_data['topic']
message=form.cleaned_data['message']
sender=form.cleaned_data.get('sender','email_address')
send_mail(
topic,
message,
sender,
['myaddress#gmail.com'],fail_silently=False
)
#return HttpResponseRedirect(reverse('games.views.thanks', {},RequestContext(request)))
return render_to_response('contact/thanks.html', {},RequestContext(request)) #good for the reverse method
else:
form=ContactForm()
return render_to_response('contact.html',{'form':form},RequestContext(request))
contact.py:
from django import forms as forms
from django.forms import Form
TOPIC_CHOICES=(
('general', 'General enquiry'),
('Gamebling problem','Gamebling problem'),
('suggestion','Suggestion'),
)
class ContactForm(forms.Form):
topic=forms.ChoiceField(choices=TOPIC_CHOICES)
sender=forms.EmailField(required=False)
message=forms.CharField(widget=forms.Textarea)
#the widget here would specify a form with a comment that uses a larger Textarea widget, rather than the default TextInput widget.
def clean_message(self):
message=self.cleaned_data.get('message','')
num_words=len(message.split())
if num_words <4:
raise forms.ValidationError("Not enough words!")
return message
Try it , this is a whole working example apps, modify it
to be send to to mailserver like a reply when it got an mail, very simple to modify it