Python email library does not add all MIME text parts - python

I added piece of code in my program. Why is it not working?
Below is the sample code:
wrapper = MIMEMultipart('mixed')
text1 = "this is a sample text"
text2 = "this is a sample msg"
part1 = MIMEText(text1, "plain")
part2 = MIMEText(text2, "plain")
wrapper.attach(part1)
wrapper.attach(part2)
output:
Part1 value is coming in msg body but part2 value is coming as attachment in mail. Why part2 value is not coming in msg body?

Send the message as a string. Try the below code. It works for me:
wrapper = MIMEMultipart('mixed')
text1 = "this is a sample text"
text2 = "this is a sample msg"
#change the message type to html type
part1 = MIMEText(text1, "html")
part2 = MIMEText(text2, "html")
#create the message to send
wrapper.attach(part1)
wrapper.attach(part2)
#finally send the message by converting it to string
server.sendmail(from, recipients, wrapper.as_string())

Related

Sending a pandas Dataframe using smtplib

I've seen a lot of threads here about this topic, however, none regarding this specific question.
I am sending a email with a pandas dataframe (df) as an html using pandas built in df.to_html() method. The email sends successfully. However, the df is displayed in the email as html, not in the desired table format. Can anyone offer assistance on how to ensure the df is displayed as a table, not in html in the email? The code is below:
import requests
import pandas as pd
import smtplib
MY_LAT =
MY_LNG =
API_KEY = ""
parameters = {
"lat": MY_LAT,
'lon': MY_LNG,
'exclude': "",
"appid": API_KEY
}
df = pd.read_csv("OWM.csv")
response = requests.get("https://api.openweathermap.org/data/2.5/onecall", params=parameters)
response.raise_for_status()
data = response.json()
consolidated_weather_12hour = []
for i in range(0, 12):
consolidated_weather_12hour.append((data['hourly'][i]['weather'][0]['id']))
hour7_forecast = []
for hours in consolidated_weather_12hour:
weather_id = df[df.weather_id == hours]
weather_description = weather_id['description']
for desc in weather_description.iteritems():
hour7_forecast.append(desc[1])
times = ['7AM', '8AM', '9AM', '10AM', '11AM', '12PM', '1PM', '2PM', '3PM', '4PM', '5PM', '6PM']
col_header = ["Description of Expected Weather"]
weather_df = pd.DataFrame(data=hour7_forecast, index=times, columns=col_header)
my_email = ""
password = ""
html_df = weather_df.to_html()
with smtplib.SMTP("smtp.gmail.com", 587) as connection:
connection.starttls() # Makes connection secure
connection.login(user=my_email, password=password)
connection.sendmail(from_addr=my_email, to_addrs="",
msg=f"Subject: 12 Hour Forecast Sterp"
"""\
<html>
<head></head>"
<body>
{0}
<body>
</html>
""".format(html_df))
just use df.to_html() to convert it into an html table that you can include in your html email
then when you send the mail you must set the mimetype to html
smtp = smtplib.SMTP("...")
msg = MIMEMultipart('alternative')
msg['Subject'] = subject_line
msg['From'] = from_addr
msg['To'] = ','.join(to_addrs)
# Create the body of the message (a plain-text and an HTML version).
part1 = MIMEText(plaintext, 'plain')
part2 = MIMEText(html, 'html')
smtp.sendmail(from_addr, to_addrs, msg.as_string())
you can use the library html2text to convert your html to markdown for clients that do not support html content (not many these days) if you do not feel like writing the plaintext on your own
as an aside... using jinja when you are working with html tends to simplify things...

Send Table contents from CSV file in Outlook Mail Body using Python

i programmed a code to send a outlook mail , which should contain the contents of CSV file as it's body , Mail part is working fine . But the table appears to be distorted .
[![MailBody][1]][1]
So here is there anyway to arrange this . and make it pretty .
and here is my code :
def sendMailt():
print("*** SENDING MAIL ****")
email_user = 'ABC#domain.com'
email_send = 'DCF#domain.com'
subject = ''
msg = MIMEMultipart()
msg['From'] = email_user
msg['To'] = email_send
msg['Subject'] = subject
body = 'Hi Team , Please Open This attachment for Folderstat Report,'
msg.attach(MIMEText(body, 'plain'))
text = """
Hello, Friend.
Here is your data:
{table}
Regards,
Me"""
with open(filtered_CSV) as input_file:
reader = csv.reader(input_file)
data = list(reader)
text = text.format(table=tabulate(data, headers=['Unnamed: 0','id','path','name','extension','size','FolderSize in GB','LastAccessTime','LastModifiedTime','LastCreationTime','folder','Total Number of files','Absolute File Count','depth','parent','uid','Oldest File Timestamp','Recent File Timestamp','Folder Modified Timestamp','Status','md5]'] ,tablefmt='orgtbl'))
server = smtplib.SMTP('domain')
sender = 'ABC#domain.com'
reciever = ['DCF#domain.com']
server.sendmail(sender, reciever, text)
server.quit()
print("Mail SEND")
and also when i receive mail , am not able to see subject or receivers ID
[1]: https://i.stack.imgur.com/y5Gxy.png
if you Use html in tablefmt you can get the data in decent format
from tabulate import tabulate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
text = """
Hello, Friend.
Here is your data:
{table}
Regards,
Me"""
with open(filtered_CSV) as input_file:
reader = csv.reader(input_file)
data = list(reader)
html = text.format(table=tabulate(data, headers="firstrow", tablefmt="html")
# for html design ( you can add whatever style you want)
html = html.replace('<table>', """<table border=1 style="
border-color:grey;
font-family: Helvetica, Arial;
font-size: 15px;
padding: 5px;">""")
server = smtplib.SMTP('domain')
msg = MIMEMultipart("alternative", None, [MIMEText(html, 'html')])
msg['From'] = from address
msg['To'] = to address
msg['Subject'] = "your subject"
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
print("Mail SEND")

How to reference variable in python html email?

I am trying to send an email with python and i have a variable ("string") from my flask route which i would like to reference in my email html.
#app.route('/edit', methods=['GET','POST'])
def edit():
...
s_list = S.query.all()
strings = '\n'.join([str(s) for s in s_list])
global string
string = str(strings)
print(string)
However, nothing appears in the variable part when the email is sent. I tried to print it on terminal and could see the results.
Can anyone let me know what am i doing wrongly please?
message = MIMEMultipart("alternative")
message["Subject"] = "Thank you."
message["From"] = sender_email
message["To"] = user_mail
# Write the plain text part
text = "Thank you for your submission! " + string
# write the HTML part
html = """\
<html>
<head></head>
<body>
<p>Thank you for your submission! <br>
""" + string + """
<br></br>
</p>
</body>
</html>
""".format(string=string)
# convert both parts to MIMEText objects and add them to the MIMEMultipart message
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)

Why when I send an attachment through a Python program the attachment don't arrive to the destination account?

I am using the next code to send an attachment through Python:
message = MIMEMultipart('alternative')
message['to'] = cliente.email
message['from'] = remitente
message['subject'] = "Solicitud en retroalimentacion".decode("utf-8")
html = ""
with open(html_send, 'r') as fichero:
html =fichero.read()
part1 = MIMEText('Vexi', 'plain')
part2 = MIMEText(html, 'html', "utf-8")
message.attach(part1)
message.attach(part2)
main_type, sub_type = content_type.split('/', 1)
print("main_type - " + str(main_type))
print("sub_type - " + str(sub_type))
print("file - " + str(file))
fp = open(file, 'rb')
attachment = MIMEBase(main_type, sub_type)
attachment.set_payload(fp.read())
fp.close()
encode_base64(attachment)
attachment.add_header('Content-Disposition','attachment;filename=attachment.pdf')
message.attach(attachment)
byte_msg = message.as_string().encode(encoding="UTF-8")
byte_msg_b64encoded = base64.urlsafe_b64encode(byte_msg)
str_msg_b64encoded = byte_msg_b64encoded.decode(encoding="UTF-8")
msg = {'raw': str_msg_b64encoded}
I review the sent mails of the origin account and it has the attachment file, but on the inbox of the destination account I only received the body of the email without the attachment file (pdf).
Do you have any idea why it does not arrive?

Sending emails with commands in python

Sometimes it works sometimes it doesn't send the emails. I don't get any error when it doesn't sent. Is there a limit or time I have to wait before sending another email?
Example Code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
if cmd == "emailA":
# Define email addresses to use
addr_to = 'toEmail'
addr_from = 'fromEmail'
# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user = 'myEmail'
smtp_pass = 'pass'
s = smtplib.SMTP(smtp_server,587)
s.starttls()
# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'Subject #1'
# Create the body of the message (a plain-text and an HTML version).
text = "Subject #1"
message = """\
<html>
<head></head>
<body>
Subject #1
</body>
</html>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(message, 'html')
msg.attach(part1)
msg.attach(part2)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
if cmd == "emailB":
# Define email addresses to use
addr_to = 'toEmail'
addr_from = 'fromEmail'
# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user = 'myEmail'
smtp_pass = 'pass'
s = smtplib.SMTP(smtp_server,587)
s.starttls()
# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'Subject #2'
# Create the body of the message (a plain-text and an HTML version).
text = "Subject #2"
message = """\
<html>
<head></head>
<body>
Subject #2
</body>
</html>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(message, 'html')
msg.attach(part1)
msg.attach(part2)
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()
I want to send emails using commands Eg. !emailA

Categories

Resources