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'
Related
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>
In my project,an email id field is available.
I am collecting the authors email id and while updating the details in database,an email should send to that particular email id,saying that book name is updated.
My views.py is
def addbook(request):
log.debug("test....")
form = BookForm
if request.POST:
form = BookForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(cd['book_name'],cd['author_name'],cd.get(''),['to#example.com'],)
form.save()
return redirect('/index/')
return render_to_response('addbook.html',{ 'form':form },context_instance=RequestContext(request))
I am using this send_mail() method to perform that but it is not working as i expected.
models.py is
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
email = models.EmailField()
bookref = models.CharField(max_length=10)
class Meta:
db_table = u'Book'
def __unicode__(self):
return "%d %s %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name,self.email,self.bookref)
forms.py
class BookForm(ModelForm):
log.debug("test....")
class Meta:
model = Book
fields=['book_id','book_name','author_name','publisher_name','email','bookref']
An mail should send to the email id mentioned in the email field.
Thanks
settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'user'
EMAIL_HOST_PASSWORD = 'password'
DEFAULT_FROM_EMAIL = 'your email'
views.py
if request.POST:
form = BookForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
email_to = cd['email']
subject = "{0} Update".format(
cd['book_name'])
message = "Author: {0}\n\n Your book name is updated".format(
cd['author_name'])
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,[email_to,])
form.save()
return redirect('/index/')
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)
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
I have a very basic email app. The forms class is:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
subject = forms.CharField(max_length=100)
sender = forms.EmailField()
recipient_list = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
cc_myself = forms.BooleanField(initial=True)
The view function looks like this:
def contact_name(request, id):
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():
name = form.cleaned_data['name']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['dennis#themenace.com']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/') # Redirect after POST
else:
a=Entry.objects.get(pk=id)
form = ContactForm(instance=a) # An unbound form
return render_to_response('email.html', {
'form': form,
})
As long as I specify the recipient in the view, I have no problem. However, I want the message to be sent to the address(es) specified in the form field "recipient list".
When I structure the view code like this:
recipients = form.cleaned_data['recipient_list']
if cc_myself:
recipients.append(sender)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/') # Redirect after POST
or:
recipients = request.POST.get('recipient_list', '')
if cc_myself:
recipients.append(sender)
I get error "'unicode' object has no attribute 'append'". In short, it doesn't work. What am I doing wrong?
Since recipient_list is an EmailField it cleans to unicode. But you're trying to treat the result as a list. So obviously, construct a list out of it and everything's dandy:
recipients = [form.cleaned_data['recipient_list']]
if cc_myself:
recipients.append(sender)
... but really you should call the field recipient not recipient list as only 1 can be entered.