My form sends the email from the account listed in my settings.py fine, but in the message I only get the subject part of the form and the message part. There is no sender part within the email, so I can't tell who would be sending the email. Does anyone know how to fix this?
My forms.py
class ContactForm(forms.Form):
subject = forms.CharField(max_length=50)
message = forms.CharField()
sender = forms.EmailField()
My Views.py contact function
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
recipients = ['otheremail#gmail.com']
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/')
else:
form = ContactForm()
return render(request, "contact.html", {'form':form,})
My Settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
That code should work fine. I have implemented the same thing below and it works, but I had one issue with gmail that you might be having.
send_mail(Subject, Message, 'myemail#example.ca', To)
The issue was that in order to have the sender be the sender I assigned when using gmail in settings - the "sender" had to be in the approved senders list within your gmail account settings.
Hope that helps.
You will have to use the EMAIL_HOST_USER as the sender because you are going to send the mail from this user account.
Please import your settings in your views.py as mentioned below.
import settings
send_mail(subject, message, settings.EMAIL_HOST_USER, recipients)
Related
I have developed a form contact where the user can contact us he will type his email, the subject and the message, But am stuck on after some tries I didn't succeed to reach my goal , everything is good the email is send to the email recipient that i have mentioned in settings.py
EMAIL_HOST_USER
But the email sender is registered as the email recipient i do no why ,Here is the code:
def contact_view(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, [settings.EMAIL_HOST_USER])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return render(request, 'pages/success.html')
return render(request, 'pages/contact.html', {'form': form})
How i can resolve that i don't want the sender email be the recipient email , i want it to be the email that user will entered during fill out the form.
Funtion send_email accepts arguments: subject, message, from_email, [to]. You are basically sending mail from and to your EMAIL_HOST_USER, because practically from_email does not matter this much (it might change name, but definitely not e-mail address itself). Backend is taken from EMAIL_HOST_USER and it's password, port etc.
Think about that on this way:
Should it be really that easy to send e-mail as any address?
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>
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'
This question already has answers here:
Email sending in django code is not working
(3 answers)
Closed 10 years ago.
I am trying to send a direct email message using django.
It doesn't produce any error, but the message are not sending to the recipient email.
Is there any problem with my codes?
VIEWS.PY
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid():
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['canonizadocharm#ymail.com']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
MODELS.PY
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
SETTINGS.PY
EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location
# Sending mail
EMAIL_USE_TLS = False
EMAIL_HOST='localhost'
EMAIL_PORT= 25
EMAIL_HOST_USER=''
EMAIL_HOST_PASSWORD=''
recipients = ['canonizadocharm#ymail.com',]
EMAIL_USE_TLS = True
EMAIL_HOST='smtp.gmail.com'
EMAIL_PORT=587
EMAIL_HOST_USER='your gmail account'
EMAIL_HOST_PASSWORD='your gmail password'
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