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.
Related
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)
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.
I have four python functions that I am using to send mail. If the program does one thing, it mails a set of results to a multiple recipients, if it does another thing, a separate function mails the results to one recipient.
def smail(to,sub,body):
addr_from = 'alert#example.com'
msg = MIMEMultipart()
msg['From'] = addr_from
msg['To'] = to
msg['Subject'] = sub
msg.attach(body)
s = smtplib.SMTP('webmail.example.com')
s.sendmail(addr_from, [to], msg.as_string())
s.quit()
def email_format2(results):
text = ""
text += 'The following applications in <environment> are non-compliant\n'
text += '<br>'
text += 'Here are there names and locations. Please inform the developer.'
text += '<br>'
text += '<br>'
table = pd.DataFrame.from_records(results)
table_str = table.to_html()
text += "%s" % table_str
return text
def mail_results_aq(results):
body = email_format2(results)
msg = MIMEText(body, 'html')
sub = "Placeholder subject"
to = 'email1#example.com, email2#example.com, email3#example.com'
smail(to, sub, msg)
def mail_results_prd(results):
body = email_format2(results)
msg = MIMEText(body, 'html')
sub = "Placeholder subject"
to = 'email4#example.com'
smail(to, sub, msg)
The mail_results_aq function will only email results to the first recipient (email1#example.com).
In other questions similar to this one, I've seen a the recipients being entered into a list i.e
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me#example.com'
recipients = ['john.doe#example.com', 'john.smith#example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())
However, this use case only seems to work when used in the same function. How can I implement this feature across the four functions I have above?
Thanks in advance!
I am trying to include a variable in the subject line of a Python email script to send a message to my phone. When I run the program, the message has "The Temp is: CTemp", but I want "The Temp is: 12.34" (or whatever the variable is set to at that time). How do I insert the variable CTemp into the subject line?
import smtplib
from email.mime.text import MIMEText
username = "****#****.com"
password = "****"
vtext = "**********#****.com"
CTemp = 12.34 #set for testing
msg = MIMEText
msg = MIMEText("""The Temp is: CTemp""")
server = smtplib.SMTP('****.****.net',25)
server.login(username,password)
server.sendmail(username, vtext, msg.as_string())
server.quit()
You should concatenate the 'Text' string to a variable
CTemp = str(12.34) #set for testing
text = "The temp is: "+CTemp
msg = MIMEText(text)
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I am trying to append the variable to (which has an email id) to msg["To"] and send the email to this list. There is no error or anything, but the email isn't being sent. As soon as I remove the to variable from msg["To"], the email is successfully sent. Where am I going wrong?
def email (body,subject,to):
msg = MIMEText("%s" % body)
msg["Content-Type"] = "text/html"
msg["From"] = "service#company.com"
msg["To"] = to + "username#company.com"
msg["Subject"] = '%s' % subject
p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
p.communicate(msg.as_string())
The problem is that if you have an e-mail address, appending a second will just run them together.
to = "address1#example.com"
msg["To"] = to + "address2#example.com"
print msg["To"]
>>> address1#example.comaddress2#example.com
Needless to say, address1#example.comaddress2#example.com is not a valid e-mail address and any MTA is going to barf on it.
Per RFC 822 and its successors, MTAs expect commas between addresses, so:
msg["To"] = to + ", address2#example.com"
should work.
Adding to=to.strip() fixed it..