Python list to html with no-bracket? - python

I am making one automatic email sending program with python for my work.
Basically, I need to send customer's list to manager everyday.
What I intended is, make a list for customer's name , make html template and send it.
It is working basically, but I hate those list's bracket.
Also I want to send beautiful list: first passenger in first sentence, second passenger in second sentence, not like every passenger in one sentence with ","
This is what I can see at this stage
import smtplib
import ssl
from email.message import EmailMessage
namelist = []
while True:
name = input("Name: ")
question = int(input("More passenger? Yes=1, No=2 "))
if question == 1:
namelist.append(name)
print(namelist)
elif question == 2:
namelist.append(name)
print(namelist)
ready_question = int(input("Ready to send email? Yes=1, No=2 "))
if ready_question == 1:
break
else:
continue
else:
namelist.append(name)
print("Press 1 or 2")
continue
subject = ""
body1 = ""
body2 = ""
body3 = "{}".format(namelist)
sender_email = ""
receiver_email = ""
password = ""
message = EmailMessage()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
html = f"""
<html>
<body>
<h1></h1>
<p>{body1}</p>
<p>{body2}</p>
<p>{body3}</p>
</body>
</html>
"""
message.add_alternative(html, subtype="html")
context = ssl.create_default_context()
print("Sending Email!")
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("Email Sent")

Also I want to send beautiful list: first passenger in first sentence,
second passenger in second sentence, not like every passenger in one
sentence with ","
You are doing
body3 = "{}".format(namelist)
which gives you python's representation of list, you might use .join method of str instance to get list elements joined by it, for example to use 3 spaces you might do:
namelist = ["Able","Baker","Charlie"]
body3 = " ".join(namelist)
print(body3)
output
Able Baker Charlie
Considering that you want names in separate lines and use HTML then I suggest you use <br> as separator, that is
body3 = "<br>".join(namelist)

Related

Python variable not updating

Basically I'm creating a program to help with my work. It will send emails to people in an excel list and move down to the next first name and email address in the list until it's done. Heres the code so far
`#AutoMail Version 2
#Goal of new version is to run on any computer. With minimal or no mouse and keyboard input
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#Random Variables
sender_address = str(input("Please enter your email address!: "))
sender_pass = str(input("Please enter your email password (No data is stored anywhere!): "))
count = 0
#This prompts user to input the file path of their CSV file.
file_path = "C:/Users/Spring/Documents/test_book_py.csv" #Change to input later!!!!!!
df = pd.read_csv(file_path, usecols=['First Name', 'Email Address'])
amount = int(input("How many emails would you like to send? "))
#Important Variables
cell_value = 0 #Which cell the info is coming from
#Cell Varialbes
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
#Gmail info Variables
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
#Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
#Emailing Process Start
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
#Email sending
while count < amount:
session.sendmail(sender_address, receiver_address, text)
cell_value = cell_value + 1
count = count + 1
print(cell_value)`
I've tried every fix I could find online for variables not updating. When I print the "cell_value" varible it prints with the updated value however the other lines in the code specifically lines 21 and 22 use that variable and they aren't using the updated varible so it is always at a constant 0 value when it should be cell_value + 1 every time the loop repeats. Is there a different way I should loop the variable updating? I need it to change that value by +1 every time so that it continues to move down the list. Keep in mind that I am a huge beginner so my code probably looks very confusing.
The issue is updating cell_value doesn't automatically updates all the data that was calculated with cell_value's old value. Once "Hello " + name_cell + ",\n\nThis is a test body" evaluates, for example, the resulting string has no relation to name_cell, and wan't change when name_cell changes. If you want that string to change when name_cell changes, you need to rerun the code that created that string.
For your case here, it looks like you could just loop over the latter half of the code. The closest to what you already have would be:
# i instead of cell_value for clarity
for i in range(amount):
name_cell = df["First Name"].values[cell_value]
email_cell = df["Email Address"].values[cell_value]
receiver_address = email_cell
email_subj = "This is a test subject"
email_body = "Hello " + name_cell + ",\n\nThis is a test body"
message = MIMEMultipart()
session = smtplib.SMTP('smtp.gmail.com', 587) #use gmail with port
session.starttls() #enable security
session.login(sender_address, sender_pass) #login with mail_id and password
message['From'] = sender_address
message['To'] = receiver_address
message['Subject'] = email_subj
message.attach(MIMEText(email_body, 'plain'))
text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
Arguably, it would be may be considered more idiomatic to zip the two .values objects that you're looping over, then islice amount-many elements from that, but I think this is cleaner.

Gmail retrive body text cwoth out b'..\r\n exmaple b'message1\r\n'

WIth this script i'd like to retreive messages from gmdail.
The expected output of the script should be message1, message2, message3, message4, message5
But the script print out the following list [b'message1\r\n', b'message2\r\n', b'message3\r\n', b'message4\r\n', b'message5\r\n']
Does anyone can help me on this?
Here is the code snippet:
import imaplib
def read_gmail():
# user and pass for login to gmail server
username = input("Enter Email Address for Login: ").lower()
password = input("Enter password for Login: ").lower()
mail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
if username == "me" and password == "me":
mail.login('mymail', 'mypass')
else:
mail.login(username, password)
mail.list()
mail.select("Inbox")
status, data = mail.search(None, 'SUBJECT "Enc Message"') # all message with Subject-> Enc Message
minimata = []
clear_lista = []
for num in data[0].split():
status, data = mail.fetch(num, '(BODY.PEEK[TEXT])') # to see the body text
minimata.append(data[0][1]) # apothikeyo se nea lista ta kryprografimena minimata.
for ch in minimata:
clear_lista.append(ch)
return clear_lista
Currently, your minimata list contains byte objects and this is where the leading b' comes from. To get rid of them you just need to decode them.
Regarding, \n and \r, you can use rstrip().
The following should do the trick:
for ch in minimata:
clear_lista.append(ch.rstrip().decode())

Python loop not running

can anyone help me fix the following code? After the question is asked, and when I reply "yes", the rest of the program doesn't run. No emails are sent.
Note that I've replaced the login data with 'example' just for this question. The actual code has valid login details
Edited the variable from "x" to "answer"
combo = open("combo.txt", "r")
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
count = str(len(combo.readlines( )))
print ("There are " + count + " amount of combos")
answer = input("Would you like to run this program?: ")
for line in combo:
pieces = line.split(":")
email = pieces[0]
password = pieces[1]
if answer == "yes":
msg = MIMEMultipart()
message = "Dear user, your Spotify account has been hacked\n" + "Your spotify email is: " + email + ", and your password is: " +password + "\n Please change your password ASAP"
passwordEmail = "example"
msg['From'] = "example#gmail.com"
msg['To'] = email
msg['Subject'] = "Spotify Account Hacked"
msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], passwordEmail)
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
As pointed out by #Robin Zigmond, you haven't declared x yet.
A useful thing whilst debugging code that is evidently not functioning, I always find, is to use print statements to check what I believe to be true. In this case, you could check immediately before the if statement by doing print(x), to see what the value was - that would have highlighted that the variable didn't exist.

Sending an e-mail by decoded login

I have two scripts, the first one is designed to write down in two separated text files an e-mail address and a password (01.txt and 02.txt). A simple Caesar algorithm is used to hide them.
In the second script, I want to uncode the mail address and the password, and then send a mail.
It's weird because when I do that, I print the right log-in and password but it won't send anything, raising the error : SMTPAuthenticationError which is not true, because with my prints I see that I typed the right information which are rightly decoded. Do you have any lead ??
mail_begin.py :
def user():
log = open("01.txt", "w")
from_add = raw_input("Your mail address is : ")
from_add = from_add.decode("utf-8")
key = 3
lettres = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
lettres = lettres.decode("utf-8")
crypted = ""
for car in from_add:
if car in lettres:
num = lettres.find(car)
num += key
if num >= len(lettres):
num = num - len(lettres)
crypted += lettres[num]
else:
crypted += car
log.write(crypted)
log.close()
def password():
log2 = open("02.txt", "w")
passw2 = raw_input("Enter your password to log-in:")
passw2 = passw2.decode("utf-8")
key = 3
lettres = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
lettres = lettres.decode("utf-8")
crypted = ""
for car in passw2:
if car in lettres:
num = lettres.find(car)
num += key
if num >= len(lettres):
num = num - len(lettres)
crypted += lettres[num]
else:
crypted += car
log2.write(crypted)
log2.close()
user()
password()
mail_finished.py
import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
msg = MIMEMultipart()
name = open("01.txt",'r')
passw = open("02.txt",'r')
f_l1 = str(name.readlines())
f_l2 = str(passw.readlines())
print (f_l1)
print (f_l2)
f_l1 = f_l1.decode("utf-8")
f_l2 = f_l2.decode("utf-8")
key = 3
lettres = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
lettres = lettres.decode("utf-8")
decrypted = ""
decrypted2 =""
for car in f_l1:
if car in lettres:
num = lettres.find(car)
num -= key
if num < 0 :
num = num + len(lettres)
decrypted += lettres[num]
else:
decrypted += car
for car in f_l2:
if car in lettres:
num = lettres.find(car)
num -= key
if num < 0 :
num = num + len(lettres)
decrypted2 += lettres[num]
else:
decrypted2 += car
msg['From'] = str(decrypted)
msg['To'] = str(decrypted)
body = "Time to go back to the lab ! Your scan is over"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
print decrypted # e-mail clear
print decrypted2 # password clear
server.login(decrypted, decrypted2) # not working, bad authentification...
text = msg.as_string()
server.sendmail(str(decrypted),str(decrypted), text)
server.quit()
name.close()
passw.close()
os.remove('01.txt')
os.remove('02.txt')
When everything is done, it erased the txt files so no one can decode them.
Could you try it at home, see where the problem is ?
Thank you
readlines() return a list, by calling str() on the list you're generating a string representation of the list.
str(['mylist'])
is
"['mylist']"
instead, you should read only the line you want, using readline not readlines - it is already a string, no need to call str() all the time:
with open("01.txt") as f:
name = f.readline().strip()
with open("02.txt") as f:
password = f.readline().strip()
Actually if I just modify :
f_l1 = (name.readlines())
f_l2 = (passw.readlines())
by
f_l1 = (name.readline())
f_l2 = (passw.readline())
it's working now. Thank you for your answer nosklo

What do I add to this code so that it reads every email?

I have some code that reads the oldest email from my gmail account, but I want it to read every email. I am very new to python, I started learning it last week. I have a lot of experience with c++ so I know what loops are I just need help implementing it in python.
What my code does is read the oldest email, then creates an int to hold the number in the subject and then gets a random number from 1 to 10 and prints whether the number in the subject in the email is equal to the random number.
I want the program to loop and do this for every email in my inbox.
import poplib
import string, random
import StringIO, rfc822
import logging
import random
SERVER = "pop.gmail.com"
USER = "XXXXXXXXXXXXXX"
PASSWORD = "XXXXXXXXXXXX"
# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
#server = poplib.POP3(SERVER)
# login
logging.debug('logging in')
server.user(USER)
server.pass_(PASSWORD)
# list items on server
logging.debug('listing emails')
resp, items, octets = server.list()
# download the first message in the list
mail = imaplib.IMAP4_SSL(SMTP_SERVER)
mail.login(FROM_EMAIL,FROM_PWD)
mail.select('inbox')
type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()
first_email_id = int(id_list[0])
latest_email_id = int(id_list[-1])
for i in range(latest_email_id, first_email_id, -1):
id, size = string.split(items[0])
resp, text, octets = server.retr(id)
# convert list to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
# output message
print(message['From']),
print(message['Subject']),
print(message['Date']),
#print(message.fp.read())
mynumber = message['Subject']
myint = int(mynumber)
print "Let's play a game! I'll choose a number between 0 and 10. Try to guess it!"
python_number = random.randint(0,10)
if python_number == myint:
print "You won! My number was " + str(python_number)
else:
print "You loose! My number was " + str(python_number)
What you want to do is instead of getting the first item
id, size = string.split(items[0])
you want to get all items:
for item in items:
id, size = string.split(item)
And then indent the code following this so it runs for each item in items
import poplib
import string, random
import StringIO, rfc822
import logging
import random
SERVER = "pop.gmail.com"
USER = "myEmail"
PASSWORD = "myPassword"
# connect to server
logging.debug('connecting to ' + SERVER)
server = poplib.POP3_SSL(SERVER)
# login
logging.debug('logging in')
server.user(USER)
server.pass_(PASSWORD)
# list items on server
logging.debug('listing emails')
resp, items, octets = server.list()
for item in items:
#For each message
id, size = string.split(item)
resp, text, octets = server.retr(id)
# convert list to Message object
text = string.join(text, "\n")
file = StringIO.StringIO(text)
message = rfc822.Message(file)
# output message
print(message['From']),
print(message['Subject']),
print(message['Date']),
#print(message.fp.read())
mynumber = message['Subject']
myint = int(mynumber)
print "Let's play a game! I'll choose a number between 0 and 10. Try to guess it!"
python_number = random.randint(0,10)
if python_number == myint:
print "You won! My number was " + str(python_number)
else:
print "You loose! My number was " + str(python_number)

Categories