Django New lines in view variable - python

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

Related

Gmail content downloader/parser

I'm trying to download all my email content from gmail using a python script but this is what I found. I tried it and it's only downloading the attachments into pdf files. Is there a way to modify it to download just the email content. I'm also trying to parse just the url links in my emails.
import email
import imaplib
import os
server = 'imap.gmail.com'
user = '#gmail.com'
password = 'pass'
outputdir = 'lolz'
subject = 'Order Completed' #subject line of the emails you want to download attachments from
def connect(server, user, password):
m = imaplib.IMAP4_SSL(server)
m.login(user, password)
m.select()
return m
def downloaAttachmentsInEmail(m, emailid, outputdir):
resp, data = m.fetch(emailid, "(BODY.PEEK[])")
email_body = data[0][1]
mail = email.message_from_bytes(email_body)
if mail.get_content_maintype() != 'multipart':
return
for part in mail.walk():
if part.get_content_maintype() != 'multipart' and part.get('Content-Disposition') is not None:
open(outputdir + '/' + part.get_filename(), 'wb').write(part.get_payload(decode=True))
#download attachments from all emails with a specified subject line
def downloadAttachments(subject):
m = connect(server, user, password)
m.select("Inbox")
typ, msgs = m.search(None, '(SUBJECT "' + subject + '")')
msgs = msgs[0].split()
for emailid in msgs:
downloaAttachmentsInEmail(m, emailid, outputdir)
downloadAttachments(subject)

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.

Python sendmail - adding header to MimeMultipart to avoid hiding all recipients

I have a code which sends an email that uses HTML for templating.
All of the recipients get the message, but all of them are BCC.
def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
global connection
if not testCurrentConnection(connection):
connect(currentConnectionName)
msg = MIMEMultipart('alternative')
subject, fromEmail, body = templateController.readTemplate(template)
header = 'To: ' + to + '\n' + 'Cc: ' + cc + 'From: ' + fromEmail + '\n' + 'Subject: ' + subject + '\n'
msg.attach(MIMEText(header, 'text'))
if subjectParams:
msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
else:
msg['Subject'] = subject
if bodyParams:
msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
else:
msg['Body'] = body
msg['From'] = fromEmail
msg['To'] = to
msg['Cc'] = cc
# no need to specify bcc here
msg.attach(MIMEText(msg['Body'], 'html'))
connection.sendmail(msg['From'], [msg['To'], msg['Cc'], bcc], msg.as_string())
del msg
I'm calling the function like this:
smtpController.sendMail("myMail#gmail.com", "ccMail#gmail.com", "", "email.html", None, None)
(The last two variables are actually a dict with key-value mapping used to populate the HTML, but the problem reproduces without them)
I read that I need to add header to my message to prevent it but for some reason, adding the header doesn't change anything (lines 7-8 in the above code).
What am I missing?
OK, I don't know how it makes a difference, but I fixed it by moving msg['To'] = to and msg['Cc'] = cc up, before Subject and Body. I completely removed the header.
def sendMail(to, cc, bcc, template, bodyParams, subjectParams):
global connection
if not testCurrentConnection(connection):
connect(currentConnectionName)
subject, fromEmail, body = templateController.readTemplate(template)
msg = MIMEMultipart('alternative')
msg['From'] = fromEmail
msg['To'] = to
msg['Cc'] = cc
if subjectParams:
msg['Subject'] = templateController.replaceTextWithParams(subject, subjectParams)
else:
msg['Subject'] = subject
if bodyParams:
msg['Body'] = templateController.replaceTextWithParams(body, bodyParams)
else:
msg['Body'] = body
msg.attach(MIMEText(msg['Body'], 'html'))
connection.sendmail(msg['From'], to.split(',') + cc.split(',') + bcc.split(','), msg.as_string())
del msg

Why is the email not sending to the recipient?

This is the code I have running, which is supposedly working totally fine, but it is not actually sending the email to the address I specify. It does not have anything to do with the CSV because I have another script doing the same thing and working just fine. The problem is that the email is being placed in the senders inbox... which is weird.
I would rather use this script since it's nicely object oriented and it has all the proper subject fields, etc.
import smtplib
import pandas as pd
class Gmail(object):
def __init__(self, email, password, recepient):
self.email = email
self.password = password
self.recepient = recepient
self.server = 'smtp.gmail.com'
self.port = 465
session = smtplib.SMTP_SSL(self.server, self.port)
session.ehlo
session.login(self.email, self.password)
self.session = session
print('Connected to Gmail account successfully.')
def send_message(self, subject, body):
headers = [
"From: " + self.email,
"Subject: " + subject,
"To: " + self.recepient,
"MIME-Version: 1.0",
"Content-Type: text/html"]
headers = "\r\n".join(headers)
self.session.sendmail(
self.email,
self.email,
headers + "\r\n\r\n" + body)
print('- Message has been sent.')
df = pd.read_csv('test.csv', error_bad_lines=False)
for index, row in df.iterrows():
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
comp_name = (row['name'])
print('Email to: ' + comp_name)
rec = (row['email'])
print('Email to: ' + rec)
gm = Gmail('email#gmail.com', 'password', rec)
gm.send_message('email to ' + comp_name, '<b>This is a test<b>')
print('-- Message for ' + rec + ' (' + comp_name + ') is completed.')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
Let me know if there is something wrong. I would really like this to work.
Just so that you can see it is working, here is the other script I am testing it against (which is poorly formatted) and it is completely functioning properly.
import smtplib
import pandas as pd
df = pd.read_csv('test.csv', error_bad_lines=False)
gmail_user = 'email#gmail.com'
gmail_password = 'password'
for index, row in df.iterrows():
sent_from = gmail_user
to = (row['email'])
subject = 'Important Message'
body = 'Hey, whats up'
rec = (row['email'])
comp_name = (row['name'])
print('Email to: ' + comp_name)
print('Email to: ' + rec)
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, to, subject, body)
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print ('-- Email sent!')
except:
print ('-- Something went wrong...')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
print('*********************************')
print('Finish reading through CSV.')
print('*********************************')
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
You should pass the recipient instead of the sender.
self.session.sendmail(
self.email,
# self.email, <- wrong here
self.recepient,
headers + "\r\n\r\n" + body)

python email sent and received with smtplib has no content

I am sending email with my raspberrypi with python.
I successfully sent and received the message, but the content is missing.
Here is my code
import smtplib
smtpUser = 'myemail#gmail.com'
smtpPass = 'mypassword'
toAdd = 'target#gmail.com'
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
msg = header + '\n' + body
print header + '\n' + body
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser,smtpPass)
s.sendmail(fromAdd, toAdd, msg)
s.quit()
Thank you for your attention!
I wrote a wrapper around sending emails in python; it makes sending emails super easy: https://github.com/krystofl/krystof-utils/blob/master/python/krystof_email_wrapper.py
Use it like so:
emailer = Krystof_email_wrapper()
email_body = 'Hello, <br /><br />' \
'This is the body of the email.'
emailer.create_email('sender#example.com', 'Sender Name',
['recipient#example.com'],
email_body,
'Email subject!',
attachments = ['filename.txt'])
cred = { 'email': 'sender#example.com', 'password': 'VERYSECURE' }
emailer.send_email(login_dict = cred, force_send = True)
You can also look at the source code to find how it works.
The relevant bits:
import email
import smtplib # sending of the emails
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
self.msg = MIMEMultipart()
self.msg.preamble = "This is a multi-part message in MIME format."
# set the sender
author = email.utils.formataddr((from_name, from_email))
self.msg['From'] = author
# set recipients (from list of email address strings)
self.msg['To' ] = ', '.join(to_emails)
self.msg['Cc' ] = ', '.join(cc_emails)
self.msg['Bcc'] = ', '.join(bcc_emails)
# set the subject
self.msg['Subject'] = subject
# set the body
msg_text = MIMEText(body.encode('utf-8'), 'html', _charset='utf-8')
self.msg.attach(msg_text)
# send the email
session = smtplib.SMTP('smtp.gmail.com', 587)
session.ehlo()
session.starttls()
session.login(login_dict['email'], login_dict['password'])
session.send_message(self.msg)
session.quit()

Categories

Resources