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.
Related
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.
I'm a very new Python coder so please don't go too harsh on me, thanks.
I'm trying to make an emailer using smtplib and I'm having trouble with handing the users credentials to Google.
Full code:
mailcheck = input("This mailer is only for gmail, want to continue? (yes or no)")
# GMAIL SMTP INFORMATION
if mailcheck == "yes" or mailcheck == "Yes" or mailcheck == "y":
smtp_server = 'smtp.gmail.com'
port = 587
set_server = "gmail"
else:
print("Hey, sorry this program is only for Gmail")
#USER CREDENTIALS + RECEIVER
username = input("Google Email?")
password = input("Password?")
receiver = input("Who to send it to?")
subject = input("Subject of the email?")
econtents = input("What to put in the email?")
amount = input("Amount of emails to send?")
credentials = username + password
global d1
global d2
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls()
server.login(username, password)
print("Sending" + amount, "to", receiver)
for i in range(1, int(amount) + 1):
message = "From" + credentials[0] + '\nSubject' + subject + '\n' + econtents
time.sleep(random.uniform(d1, d2))
server.sendmail(credentials[0], receiver, message)
print("\nEmail Sent!")
else:
print("Finished sending emails")
except smtplib.SMTPRecipientsRefused:
print("Recipient refused. Invalid email address?")
except smtplib.SMTPAuthenticationError:
print("Unable to authenticate with server. Ensure the details are correct.")
except smtplib.SMTPServerDisconnected:
print("Server disconnected for an unknown reason.")
except smtplib.SMTPConnectError:
print("Unable to connect to server.")
The error :
Unable to authenticate with server. Ensure the details are correct.
This means it went wrong with the login process. It should be going wrong somewhere in this part:
#USER CREDENTIALS + RECEIVER
username = input("Google Email?")
password = input("Password?")
receiver = input("Who to send it to?")
subject = input("Subject of the email?")
econtents = input("What to put in the email?")
amount = input("Amount of emails to send?")
credentials = username + password
global d1
global d2
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls()
server.login(username, password)
print("Sending" + amount, "to", receiver)
for i in range(1, int(amount) + 1):
message = "From" + credentials[0] + '\nSubject' + subject + '\n' + econtents
time.sleep(random.uniform(d1, d2))
server.sendmail(credentials[0], receiver, message)
print("\nEmail Sent!")
I think it's because of the credentials = username + password which doesn't work, but I have no idea how I'd fix it.
If anyone knows what I'd have to change to fix this that'd be great!
Instead of adding those two strings, you're meaning to put them in an array. In Python, that's either
credentials = [username, password]
or
credentials = list(username, password)
But that doesn't seem to be your issue. Your issue is related to the login() function as you get the SMTPAuthenticationError exception. The smtplib documentation says that after running .starttls(), you should run .ehlo() again. Try to run that before logging in. Additionally, you could try to generate an SSL instance on port 465.
(Ctrl+F for .starttls())
https://docs.python.org/2/library/smtplib.html
I searched about this quite a lot, but could not fix the issue in my script. So finally, I decided to post it here.
Here's the code snippet:
fromaddr = "someValidAddress#xyz.com"
cc = ['SomeEmailAlias#xyz.com']
toaddr = ""
msg = MIMEMultipart()
toaddrlist = list(toaddr.split(',')) #As sendmail() accepts the list of recipients only in list form.
toaddrlist += (cc,)
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Cc'] = ', '.join(cc)
msg['Date'] = formatdate(localtime=True)
msgHtml = MIMEText(html, 'html')
msg.attach(msgHtml)
msg['Subject'] = "Test mail"
server = "someMailServer.xyz.com"
smtp = smtplib.SMTP(server, 25)
smtp.sendmail(fromaddr, toaddrlist, msg.as_string())
smtp.close() #Close the SMTP server connection.
I'm aware and I've ensured that msg['To'] accepts a string value (toaddr), whereas toaddrlist in sendmail() should be a list.
Catch: If I remove the line toaddrlist += (cc,), then the mail does not get delivered twice to the recipients in "To" field, but the mail does not get delivered to the Cc alias.
Please help.
When the line toaddrlist += (cc,) is evaluated, the value of toaddrlist in your case is :
["", ["SomeEmailAlias#xyz.com"]]
and it's wrong because toaddrlist must be a list of strings not a list containing some lists.
So the solution is to change :
toaddrlist += (cc,)
to
toaddrlist += cc
or the recommended form (the pythonic way) :
toaddrlist.extend(cc)
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
This program works quite well except for when dealing with logging in with Gmail. I wasn't quite sure if this was a problem with Gmail specifically, or a problem with my program. Comcast, AOL, and Yahoo! work fine.
import socket
import smtplib
email_provider = raw_input('Gmail, AOL, Yahoo! or Comcast? ').title()
email_user = raw_input('Type in your full email username. ')
email_pwd = raw_input('Type in your email password. ')
if email_provider == 'Gmail' or 'Google':
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
if email_provider == 'Aol' or 'AOL':
smtpserver = smtplib.SMTP("smtp.aol.com",587)
if email_provider == 'Yahoo' or 'Yahoo!':
smtpserver = smtplib.SMTP("smtp.mail.yahoo.com",587)
if email_provider == 'Comcast' or 'Xfinity':
smtpserver = smtplib.SMTP("smtp.comcast.net",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(email_user, email_pwd)
sendto = raw_input('Email address to send message to: ')
to = sendto
CC = sendto
subj = raw_input('Subject: ')
header = 'To: ' + to + '\n' + 'From: ' + email_user + '\n' + 'Subject:' + subj +'\n'
print '\nMessage Details:'
print (header)
assignment=raw_input('Enter your message: ')
msg = header + assignment + '\n'
smtpserver.sendmail(email_user, to, msg)
print ('Your message has been sent!')
smtpserver.close()
This is a problem:
if email_provider == 'Gmail' or 'Google':
Python works on truthy values. Anything that isn't False, None, 0 or an empty collection/mapping will be True.
From what it looks like, the execution chain will fall all the way through until it sets your SMTP connection credentials to Comcast's server.
So, effectively, your first statement is saying this:
if email_provider == 'Gmail' or True
You would want to change it to this:
if email_provider in ('Gmail', 'Google')
Then, realistically, those could be rewritten as elif - only one of those statements are going to be true at any given time.