Django email: Get receiver in body - python

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?

Related

How to change plain message into html message in django?

I'm getting string representation of html code in email.. How can i get proper html email ?
message1 = (subject, 'Here is the message', from_email, recipient_list)
message2 = (subject, html_message, from_email, recipient_list)
message2.content_subtype = "html"
send_mass_mail((message1, message2), fail_silently=False)
This might help you...
msg = "Here is the message"
message1 = (subject, msg, from_email, recipient_list)
html_message = "<p>" + msg + "</p>"
message2 = (subject, html_message, from_email, recipient_list)
message2.content_subtype = "html"
send_mass_mail((message1, message2), fail_silently=False)
Here I declared a variable for the message msg which can be concatenated with the html tag you want (here it is <p> tag) using the concatenation operator +
Thank you!

Django-Email, sending multiple email depends on Email ID

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.

EmailMultiAlternatives no connection could be made because the target machine actively refused it

I'm trying to make an ajax request to will generate a password for a user and send them an email with the password. This all works fine, except for the error I'm getting at msg.send()
Ajax:
<script type="text/javascript">
var frm = $('#retrieveKeyForm');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
Views.py
class GenerateSecretKey(APIView):
def get(self, request):
#Get email address from request
emailaddr = request.GET.get('email')
print(emailaddr)
#Show the email address(for debugging)
min_char = 10
max_char = 12
allchar = string.ascii_letters + string.digits
#Generate passsword
password = "".join(choice(allchar) for x in range(randint(min_char, max_char)))
print("Your password is {}".format(password))
subject, from_email, to = 'Your key is ready!', 'test#test.com', emailaddr
html_content = render_to_string('testapp/email.html', {'password':password})
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
return Response({'Success':'Your key has been generated. Please check your email.'})
Error:
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
This block of code worked much better. I hadn't configured an SMTP server or specified any SMTP details so that's why I was getting that error. Special thanks to this guy https://github.com/llamafarmer/email/blob/master/sendEmailAttachment.py
fromaddr = "test#test.com"
toaddr = request.GET.get('email')
print(toaddr)
smtp_user = "test#gmail.com"
smtp_pass = "abctest"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Ready!"
body = render_to_string('testapp/email.html', {'password':password})
msg.attach(MIMEText(body, 'html'))
server = smtplib.SMTP('in-v3.mailjet.com', 587)
server.starttls()
server.login(smtp_user, smtp_pass)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
return Response({'Success':'Your key has been generated. Please check your email.'})

Django New lines in view variable

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

Django sending e-mail u'' around headers

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']

Categories

Resources