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.
Related
I am sending email with Django using Sendgrid. I have a variable message for the message that will send, however the message holds the value of a few other variables. I would like them to be on different lines to make the email easier to read. Here is what I have, although it is not working.
if form.is_valid():
name = form.cleaned_data.get('name')
phone = form.cleaned_data.get('phone')
email = form.cleaned_data.get('email')
party_size = form.cleaned_data.get('party_size')
form_message = form.cleaned_data.get('message')
listing_address = listing.address
message = name + "\n" + phone + "<br>" + email + "<br>" + party_size + "<br>" + listing_address
send_mail('New Lead', message, 'to email', ['email#gmail.com'], fail_silently=False)
The email is being sent as this:
garrett 1234234<br>g#d.com<br>2<br>address would be here
Although I would like this:
garrett
1234234
g#d.com
2
address would be here
The best way is to create email template & provide context to email template then use generate email content. Use this content(generated_html) in send_email
as parameter html_message
send_mail('New Lead', message, 'to email',
['email#gmail.com'], fail_silently=False, html_message=genenrated_html)
You can send HTML version of email with EmailMessage:
from django.core.mail import EmailMessage
message = name + "<br>" + phone + "<br>" + email + "<br>" + party_size + "<br>" + listing_address
msg = EmailMessage(subject, message, from_email, ['email#gmail.com'])
msg.content_subtype = "html" # Main content is now text/html
msg.send()
trata utilizando el siguiente codigo:
if form.is_valid():
name = form.cleaned_data.get('name')
phone = form.cleaned_data.get('phone')
email = form.cleaned_data.get('email')
party_size = form.cleaned_data.get('party_size')
form_message = form.cleaned_data.get('message')
listing_address = listing.address
message = "<html><body><p>" name + "</p><br><p>" + phone + "</p>
<br><p>" + email + "</p><br><p>" + party_size + "</p><br><p>" +
listing_address + "</p><br></body></html>"
msg = EmailMessage(subject, message, from_email,['email#gmail.com'])
msg.content_subtype = "html" # El contenido ahora sera text/html
send_mail('New Lead', message, 'to email', ['email#gmail.com'], fail_silently=False)
No need to change the django snippet that you have given here
In Sendgrid there is a setting to do this
In the settings page where you need to make the status as on. All your plain text will be converted / parsed to HTML view
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 am using EmailMultiAlternatives to send mail to a list of recipients.
context = Context({'cc': cc, 'link': link})
html_template = loader.get_template('email_new.html')
text_template = loader.get_template('email_new.txt')
from_email = 'afeld <afeld#has_questions.com>'
recipient_list = ['%s <%s>' % (e.full_name(), e.email()) for e in cc.not_responded()]
cc_list = ['%s <%s>' % (e.full_name(), e.email()) for e in cc.notification_recipients()]
message = EmailMultiAlternatives(
subject,
text_template.render(context),
from_email,
to=recipient_list,
cc=cc_list
)
Is it possible to get the recipient of an email inside the body? Something that would look like in my email.html
dear {{ recipient }}
from afeld
How would I get {{ recipient }} from recipient_list?
I am trying to send an email with an image using smtplib in python. The email shows up fine on my desktop and on the iphone gmail app, but on the standard iphone mail app the body doesn't appear. Here is my code:
def send_html_email(self, subject, html, to_email,from_email, password, from_name, image=None):
msg = MIMEMultipart('alternative')
msg['From'] = from_name
msg['To'] = to_email
msg['Subject'] = subject
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msg.as_string().encode('utf-8'))
session.quit()
It seems that when I do not add an image, the email sends fine with the body. Any ideas on how to get it working with the image as well?
This appears to work:
def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
msgRoot = MIMEMultipart('related')
msgRoot['From'] = from_name
msgRoot['To'] = to_email
msgRoot['Subject'] = subject
msg = MIMEMultipart('alternative')
msgRoot.attach(msg)
html_message = MIMEText(html, "html")
msg.attach(html_message)
if image:
msgImage = MIMEImage(image)
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
session = smtplib.SMTP("smtp.gmail.com:587")
session.starttls()
session.login(from_email, password)
session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
session.quit()
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']