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
Related
I am working with the below code to send emails to customer and as you guys know there is daily sending limits set by different companies.
What I want to achieve is to change email credentials before reaching limit but continue with the recipient list.
For example: I have 5 email credentials each email id will 50 emails and will change automatically.
Code I work with:
import smtplib
li = ["xxxxx#gmail.com", "yyyyy#gmail.com"]
for dest in li:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login("sender_email_id", "sender_email_id_password")
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
s.quit()
Get the index of the destination in its list, and transform that into an index into the credentials list.
for i, dest in enumerate(li):
if i//50 >= len(credentials):
print("Ran out of credentials")
break
creds = credentials[i//50]
// use credentials to send mail
clients = ["xxxxx#gmail.com", "yyyyy#gmail.com"]
chunk_size = 50
chunks = (clients[i:i+chunk_size] for i in range(0,len(clients), chunk_size))
creds = [("sender_email_id_1", "sender_email_id_password_1"), ("sender_email_id_2", "sender_email_id_password_2")]
for i,chunk in enumerate(chunks):
try:
user, pw = creds[i]
except IndexError:
print("Ran out of credentials")
raise
for client in chunk:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(user, pw)
message = "Message_you_need_to_send"
s.sendmail(user, client, message)
s.quit()
If you'd rather not throttle yourself, but would like to keep trying to send as many emails as possible:
clients = ["xxxxx#gmail.com", "yyyyy#gmail.com"]
creds = [("sender_email_id_1", "sender_email_id_password_1"), ("sender_email_id_2", "sender_email_id_password_2")]
for cred,client in zip(itertools.cycle(creds), clients):
user, pw = creds
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(user, pw)
message = "Message_you_need_to_send"
s.sendmail(user, client, message)
s.quit()
The following uses a generator nextcred to loop over the credentials in a list until you have sent all the messages. It wraps back to the first pair after you have looped over the whole list.
We use one pair to send 50 messages, then log out and back in with the next pair of credentials.
import smtplib
def nextcred():
credentials = [('user', 'password'), ('plugh', 'xyzzy'), ('alfred', 'what me worry?')]
while True:
for tup in credentials:
yield tup
li = ["xxxxx#gmail.com", "yyyyy#gmail.com"]
cred = nextcred()
s = None
for idx, dest in enumerate(li):
if (idx % 50) == 0:
if s:
s.quit()
account, passw = next(cred)
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(account, passw)
message = "Message_you_need_to_send"
s.sendmail("sender_email_id", dest, message)
s.quit()
As an aside, I hope you are not really constructing your SMTP messages by pasting together strings. The Python email library takes care of a mound of corner cases and complications which are hard to get right and impossible to guess how to solve if you are not intimately familiar with SMTP and MIME.
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 need to check a lot emails, thousands of emails.
I use smtplib to do it and I have some problem.
It's takes too much time (although I use multiprocessing and as usual 32 processes).
And sometimes I have an error to some email (timeout) or another error and I don't take any result for this.
But If I execute it again, I won't get an error, but can get errors for another email.
What I do wrong in my code and how can I improve that to have more accuracy and less errors.
def check_email(email, mxRecord):
time.sleep(2)
host = socket.gethostname()
try:
server = smtplib.SMTP()
server.set_debuglevel(0)
addressToVerify = email
server.connect(mxRecord)
server.helo(host)
server.mail('me#domain.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
if code == 250:
res_email = email
res = str(num) + ' ' + str(res_email)
print res
return res
else:
continue
except:
continue
you just loop throu all mail at the same time use threading...
def check_email(email, mxRecord):
time.sleep(2)
host = socket.gethostname()
for line, line 1 in itertools.izip(email, mxRecord)
try:
server = smtplib.SMTP()
server.set_debuglevel(0)
addressToVerify = email
server.connect(mxRecord)
server.helo(host)
server.mail('me#domain.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
if code == 250:
res_email = email
res = str(num) + ' ' + str(res_email)
print res
return res
else:
continue
except:
continue
m = threading.Thread(name='daemon', target=check_email(email,mxRecord))
m.setDaemon(True)
m.start()
sould look like this
I am making a simple script for send mail through gmail account in python 2.7.5.. Before send mail i wanna check that whether user successfully login through gmail smtp or not... Here is my code:
#!/usr/bin/python
import smtplib
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt = raw_input("Enter Receipt email address: ")
subject = raw_input ("Subject: ")
msg = raw_input("Message: ")
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (user, ", ".join(receipt), subject, msg)
smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo
print "Connecting to the server....."
try:
session.login(user, password)
if (session.verify(True)):
print "Connected to the server. Now sending mail...."
session.sendmail(user, receipt, message)
session.quit()
print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
print "Can not connected to the Server...!"
print "Simple mail Test"
But when i run it, then it will give "Can not Connected to the Server". can any body help me what i am doing wrong?
You just forgot a couple of things. The receipt have to be a list, and the verify method take the user email as argument. Here's the code with some improvements:
#!/usr/bin/python
import smtplib
receipt,cc_list=[],[]
user = raw_input("Enter Your email address: ")
password= raw_input("Enter your email password: ")
receipt.append(raw_input("Enter Receipt email address: "))
subject = raw_input ("Subject: ")
message = raw_input("Message: ")
header = 'From: %s\n' % user
header += 'To: %s\n' % ','.join(receipt)
header += 'Cc: %s\n' % ','.join(cc_list)
header += 'Subject: %s\n\n' % subject
message = header + message
smtp_host = 'smtp.gmail.com'
smtp_port = 587
session = smtplib.SMTP()
session.connect(smtp_host, smtp_port)
session.ehlo()
session.starttls()
session.ehlo
print "Connecting to the server....."
try:
session.login(user, password)
if (session.verify(user)):
print "Connected to the server. Now sending mail...."
session.sendmail(user, receipt, message)
session.quit()
print "Mail have been sent successfully.....!"
except smtplib.SMTPAuthenticationError:
print "Can not connected to the Server...!"
print "Simple mail Test"
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.