I am trying to send two different emails using the django send_mass_mail function. I'm very new to django, and I'm struggling to get it to work. The send-Mail function works fine when I use it, but I want to send different emails to the customer and the site owner when a purchase is made. Any help with this would be amazing! Thanks so much!
def _send_confirmation_email(self, order):
""" Send the user a confirmation email """
cust_email = order.email
subject = render_to_string(
'checkout/confirmation_emails/confirmation_email_subject.txt',
{'order': order})
body = render_to_string(
'checkout/confirmation_emails/confirmation_email_body.txt',
{'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL})
subject2 = render_to_string('Order Placed', {'order':order})
body2 = render_to_string(
'An order has been placed',
{'order': order}
)
message1 = (
subject,
body,
settings.DEFAULT_FROM_EMAIL,
[cust_email]
)
message2 = (
subject2,
body2,
settings.DEFAULT_FROM_EMAIL,
['test#hotmail.com']
)
send_mass_mail((message1, message2), fail_silently=False)
Related
I try to send an email to more than one recipients but I am doing something wrong. I'm using a for loop to get the email addresses from the user. If I print the emails these are in this format: 'someone#xy.com' and I have more than one.
But if I try to send them the email, only one user gets the it.
It sends the mail every time if the html in the urls.py is refreshed.
views.py
from django.shortcuts import render
from django.core.mail import send_mass_mail
from somemodels.models import Project
import datetime
import calendar
def emails(request):
today = datetime.date.today()
weekday = today.weekday()
month = datetime.date.today().month
year = datetime.date.today().year
cal = calendar.monthrange(year, month)[1]
firstday = datetime.date.today().replace(day=1)
subject='hello'
message='how are you?'
from_email='myemail#gmail.com'
for p in Project.objects.raw('SELECT * FROM somemodels_project INNER JOIN auth_user ON auth_user.id = othermodel_project.permitted_users'):
recipient_list = p.email,
print(recipient_list)
if (today == firstday):
messages = [(subject, message, from_email, [recipient]) for recipient in recipient_list]
send_mass_mail(messages)
print('Successfully sent')
else:
print('Not sent')
return render(request, 'performance/emails.html')
urls.py
app_name = 'email'
urlpatterns = [
path('emails/', login_required(views.emails), name='emails'),
]
Get the list of people to send the email to
https://docs.djangoproject.com/en/4.0/topics/db/sql/
recipient_list = Project.objects.raw(...)
If your message doesn't change you can also use
send_mail(
subject,
message,
from_email,
[r.email for r in recipient_list],
)
If you want to use mass mail because it is more efficient
https://docs.djangoproject.com/en/4.0/topics/email/
messages = [(subject, message, from_email, [r.email]) for r in recipient_list]
send_mass_mail(messages)
Anyone know how to solved my issue, Im working with DJango-email with multiple recipient. Sending email in multiple recipient accounts from my DB are working, but now I want to send email and the email:body are depending on the Data ID.
This are the email list,
Scenario: Plate_No: 123123 will be send to example_email1#gmail.com only and ABV112 will be send again to example_email2#gmail.com and so on. Only the Plate_no assign in email will send, can someone help me to work my problem. Thank you!
auto send email script:
class HomeView(ListView):
cstatus = VR.objects.filter(Deadline__date = datetime.datetime.today(), sent_email="No")
print(cstatus)
recipient_list = []
for recipient in cstatus:
recipient_list.append(recipient.email)
print(recipient_list)
plate = ""
for carreg in cstatus:
print(carreg.plate_no)
plate = carreg.plate_no
if plate != "":
subject = 'FMS Automated Email'
html_message = render_to_string('vr/pms_email.html', {'content':cstatus})
plain_message = strip_tags(html_message)
from_email = 'FMS <fms#gmail.com>'
mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False)
cstatus.update(sent_email="Yes")
model = VR
context_object_name = 'list'
template_name = 'vr/list.html'
You can use a for-loop on your cstatus queryset to send the emails to the recipents. Did not test it, but it should look something like this:
for item in cstatus:
subject = 'FMS Automated Email'
html_message = render_to_string('vr/pms_email.html'{'content':item.Plate_no})
plain_message = item.Plate_no
recipent_list = [item.email]
from_email = 'FMS <fms#gmail.com>'
mail.send_mail(subject, plain_message, from_email, recipient_list, html_message=html_message, fail_silently=False)
item.update(sent_email="Yes")
According to what I understood regarding your query, this might what you need:
class HomeView(ListView):
cstatus = VR.objects.filter(Deadline__date = datetime.datetime.today(), sent_email="No")
print(cstatus)
recipient_list = {}
for recipient in cstatus:
recipient_list[recipient.plate_no] = recipient.email
print(recipient_list)
for carreg in cstatus:
print(carreg.plate_no)
plate = carreg.plate_no
if plate != "":
subject = 'FMS Automated Email'
html_message = render_to_string('vr/pms_email.html', {'content':carreg}) # or use plate for just plate_no
plain_message = strip_tags(html_message)
from_email = 'FMS <fms#gmail.com>'
mail.send_mail(subject, plain_message, from_email, [recipient_list[plate]], html_message=html_message, fail_silently=False)
cstatus.update(sent_email="Yes")
model = VR
context_object_name = 'list'
template_name = 'vr/list.html'
Or Use mass emailing in django:
link: https://docs.djangoproject.com/en/1.8/topics/email/#send-mass-mail
message1 = ('Subject here', 'Here is the message', 'from#example.com', ['first#example.com', 'other#example.com'])
message2 = ('Another Subject', 'Here is another message', 'from#example.com', ['second#test.com'])
send_mass_mail((message1, message2), fail_silently=False)
Add all the above message results in a tuple and add it in send_mass_mail. For eg.
datatuple = (
(subject, plain_message, from_email, to_email),
(subject, plain_message, from_email, to_email)
) # to_mail -> recipient_list[plate]
send_mass_mail(datatuple)
Let me know if I was wrong.
Ive built an contact form which sends an email. I'm just having a bit of trouble in relation to the account its being sent to. I want the email to be sent from "servwishes#gmail.com" to the "Contact_Email".
Right now the email is going from "Contact_Email" to "servwishes#gmail.com".
my views.py looks like this:
def contact(request):
Contact_Form = ContactForm
if request.method == 'POST':
form = Contact_Form(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name')
contact_email = request.POST.get('contact_email')
contact_content = request.POST.get('content')
template = get_template('users/contact_form.txt')
context = {
'contact_name' : contact_name,
'contact_email' : contact_email,
'contact_content' : contact_content,
}
content = template.render(context)
email = EmailMessage(
"New contact form email",
content,
"Creative web" + '',
['servwishes#gmail.com'],
headers = { 'Reply To': contact_email }
)
email.send()
return render(request, 'users/contact.html', {'form':Contact_Form })
And my setting.py looks like:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'servwishes#gmail.com'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
If you look at the order of your arguments and convert them from positional to keyword, you currently have:
email = EmailMessage(
subject="New contact form email",
body=content,
from_email="Creative web" + '',
to=['servwishes#gmail.com'],
headers = { 'Reply To': contact_email }
)
I think there were a couple of issues here. I think you probably meant to do:
from_email='"Creative web" <servwishes#gmail.com>'
But since you didn't get that, it messed up the order of your positional arguments.
To should be to=contact_email
The other issue is I think you are misunderstanding the 'Reply To' header. That's who, when the recipient hits the reply button, the email will be sent back to. It is not who you are sending the email to.
Im triying to send a mass email with django's "send_mass_email" method, i've read the documentation but the examples only show plain text messages.
How can i be able to send HTML messages with the "send_mass_emal" method? i tried like a regular email but the recived only html code. Here is my code:
for row_index in range(12, sheet.nrows):
if sheet.cell(rowx=row_index, colx=0).value != "":
template = get_template("MonthlyEmail.html")
context = Context({
'name': str(clean_string(sheet.cell(rowx=row_index, colx=2).value)),
'doc_type': str(sheet.cell(rowx=row_index, colx=4).value),
'document': str(sheet.cell(rowx=row_index, colx=3).value),
'email': str(sheet.cell(rowx=row_index, colx=5).value),
'acc_numb': str(sheet.cell(rowx=row_index, colx=6).value),
'brute_salary': str(sheet.cell(rowx=row_index, colx=8).value),
'vacation_commision': str(sheet.cell(rowx=row_index, colx=9).value),
'brute_total': str(sheet.cell(rowx=row_index, colx=10).value),
'social_sec': str(sheet.cell(rowx=row_index, colx=14).value),
'isr': str(sheet.cell(rowx=row_index, colx=27).value),
'other_retention': str(sheet.cell(rowx=row_index, colx=13).value),
'net_payment': str(sheet.cell(rowx=row_index, colx=29).value)
})
content = template.render(context)
messages.append(('Monthly Salary Report', content,
'intranet#intranet.com',
[str(sheet.cell(rowx=row_index, colx=5).value)]))
send_mass_mail_html(messages, fail_silently=False)
It does not look like send_mass_email() supports HTML emails. But there is a way to do it by taking inspiration from the code of Django's send_mail() function:
connection = connection or get_connection(
username=auth_user,
password=auth_password,
fail_silently=fail_silently,
)
mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, connection=connection)
if html_message:
mail.attach_alternative(html_message, 'text/html')
mail.send()
The general strategy seems to create a connection first, then for each email you need to send, create an instance of EmailMultiAlternatives, passing it the existing connection, then send it, exactly as send_mail but in a loop...
I have wrote my own functionality to use mass email by using the django documentaion as reference.
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def get_rendered_html(template_name, context={}):
html_content = render_to_string(template_name, context)
return html_content
def send_email(subject, html_content, text_content=None, from_email=None, recipients=[], attachments=[], bcc=[], cc=[]):
# send email to user with attachment
if not from_email:
from_email = settings.DEFAULT_FROM_EMAIL
if not text_content:
text_content = ''
email = EmailMultiAlternatives(
subject, text_content, from_email, recipients, bcc=bcc, cc=cc
)
email.attach_alternative(html_content, "text/html")
for attachment in attachments:
# Example: email.attach('design.png', img_data, 'image/png')
email.attach(*attachment)
email.send()
def send_mass_mail(data_list):
for data in data_list:
template = data.pop('template')
context = data.pop('context')
html_content = get_rendered_html(template, context)
data.update({'html_content': html_content})
send_email(**data)
message1 = {
'subject': 'Subject here',
'text_content': 'Here is the message',
'from_email': 'from#example.com',
'recipients': ['first#example.com', 'other#example.com'],
'template': "template1.html",
'context': {"d1": "mydata"}
}
message2 = {
'subject': 'Subject here',
'text_content': 'Here is the message',
'from_email': 'from#example.com',
'recipients': ['first#example.com', 'other#example.com'],
'template': "template2.html",
'context': {"d2": "mydata"}
}
send_mass_mail([message1, message2])
Reference: https://docs.djangoproject.com/en/1.11/_modules/django/core/mail/#send_mass_mail
I wrote custom mass mail method and it is working fine:-
from django.core.mail.message import EmailMessage
from django.core.mail import get_connection
def send_custom_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
"""
coloned fromt he core
"""
connection = connection or get_connection(
username=auth_user,
password=auth_password,
fail_silently=fail_silently,
)
EmailMessage.content_subtype = 'html'
messages = [
EmailMessage(subject, message, sender, recipient, connection=connection)
for subject, message, sender, recipient in datatuple
]
return connection.send_messages(messages)
Then I use as per document:
send_custom_mass_mail((mail_to_lead), fail_silently=False)
I wrote a simple contact form for a client in Django. However, whenever it sends e-mail, it wraps the header values in u'' objects. For example, the From: header is
From: (u'my#email.com',)
Here's the code that sends the message:
The form:
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
sender = forms.EmailField()
subject = forms.CharField(max_length=255)
message = forms.CharField(widget=forms.widgets.Textarea(attrs={'rows':15, 'cols': 72}))
The contact function:
def contact(request):
RECAPTCHA_PRIVATE_KEY = '******************'
captcha_error = ''
if request.method == 'POST':
form = ContactForm(request.POST)
captcha_response = captcha.submit(request.POST.get("recaptcha_challenge_field", None),
request.POST.get("recaptcha_response_field", None),
RECAPTCHA_PRIVATE_KEY,
request.META.get("REMOTE_ADDR", None))
if not captcha_response.is_valid:
captcha_error = "&error=%s" % captcha_response.error_code
elif form.is_valid():
name = form.cleaned_data['name'],
sender = form.cleaned_data['sender'],
subject = form.cleaned_data['subject'],
message = form.cleaned_data['message']
recipients = ['email#email.com']
try:
send_mail(subject, message, sender, recipients)
except BadHeaderError:
pass
flash_message = 'Thank you for contacting us. We will get back to you shortly.'
return render_to_response('pages/contact.html', {
'form': form,
'captcha_error': captcha_error,
'message': flash_message
})
It sends the e-mail perfectly, I check the appropriate mailbox and the e-mail appears. But these u'' objects prevent the e-mail's subject from appearing correctly and prevents it from being replied to.
What am I doing wrong?
Thanks in advance.
Lose the trailing commas here:
elif form.is_valid():
name = form.cleaned_data['name']
sender = form.cleaned_data['sender']
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']