Printing subjects and sender from email in python - python

I'm trying to get a python script which looks through my gmail inbox using imap and prints out the subject and sender of any emails which are unseen. I've started but at the moment I don't think it can sort the unseen emails or extract from these the subject and sender.
Does anyone know how to finish this code?
import imaplib
import email
user = "x"
password = "y"
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user, password)
mail.list()
mail.select('inbox')
unseen_emails = mail.search(None, 'UnSeen')
print unseen_emails

If you were willing to use poplib, this should work.
import poplib
mymail = []
host = "pop.gmail.com"
mail = poplib.POP3_SSL(host)
print (mail.getwelcome())
print (mail.user("user#gmail.com"))
print (mail.pass_("password"))
print (mail.stat())
print (mail.list())
print ("")
if mail.stat()[1] > 0:
print ("You have new mail.")
else:
print ("No new mail.")
print ("")
numMessages = len(mail.list()[1])
numb=0
for i in range(numMessages):
for j in mail.retr(i+1)[1]:
numb+=1
if numb == 4 or numb == 5:
print(j)
mail.quit()
input("Press any key to continue.")
Just be sure to allow less secure apps in your google account here: https://myaccount.google.com/lesssecureapps

My external lib https://github.com/ikvk/imap_tools
from imap_tools import MailBox, AND
# get list of unseen emails from INBOX folder
with MailBox('imap.mail.com').login('test#mail.com', 'pwd', 'INBOX') as mailbox:
for msg in mailbox.fetch(AND(seen=False)):
msg.subject # str: 'some subject 你 привет'
msg.from_ # str: 'Sender#ya.ru'
NOTE: mailbox.fetch has mark_seen arg!

Related

How would I use imaplib to check if an email is received from a certain email address and then trigger a selenium action?

My code so far
import base64
email_user = input('Email: ')
email_pass = input('Password: ')
M = imaplib.IMAP4_SSL('imap.gmail.com', 993)
M.login(email_user, email_pass)
M.select()
typ, message_numbers = M.search(None, 'ALL') # change variable name, and use new name in for loop
for num in message_numbers[0].split():
typ, data = M.fetch(num, '(RFC822)')
# num1 = base64.b64decode(num) # unnecessary, I think
print(data) # check what you've actually got. That will help with the next line
data1 = base64.b64decode(data[0][1])
print('Message %s\n%s\n' % (num, data1))
M.close()
M.logout()
My code currently prints out all of my emails
It prints out a load of text, but how would I refine it to see if an email from an email address is received and then trigger opening a website.

mail-client issue in Python

My script should take the user inputs and login to the server but when I give it the inputs it false and I tried different servers and different emails and the passwords are correct. How can I determine what's wrong?
import smtplib
sent = 'true'
ss = 'true'
repeat = 1
while sent == 'true':
m_email = input ('Enter Your Email Address: ')
m_server = input ('Entere Your Email Server: ')
m_auth = input ('username?\n')
p_auth = input ('password?\n')
r_email = input ('enter the reciver email: ')
subject = input ('enter Your Subject: ')
subject = 'subject '+ subject
m_massege = input ('Your Massege: ')
massege = subject + '\n \n' + m_massege
while ss == 'true' or repeat == "5" :
try:
server = smtplib.SMTP(m_server)
server.ehlo()
server.starttls()
server.login(m_auth,p_auth)
server.Sendmail(m_email,r_mail,massege)
print ("Mail Sent Successfully!")
sent = 'false'
except:
print ('sending failed')
repeat =+ 1
exit()
I've also had issues with smtplib and what I found was that it was not actually a code issue but rather an issue with the email account. For example, in my case I was trying to log into my yahoo mail account to automate emails and it kept failing so I had to go to my yahoo account security settings and enable "allow unsecured application login".
Point is: the problem isn't with your code but with the security settings on the email accounts (For me neither gmail nor yahoo worked).

Fetch all emails from gmail of a particular label

I want to fetch all the emails from gmail of a particular label called important. I am using imaplib and python 2.
Below is my code,
import email, getpass, imaplib, os
detach_dir = '.'
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("important")
resp, items = m.search(None, "ALL")
items = items[0].split()
print len(items)
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
if mail.get_content_maintype() != 'multipart':
continue
print "["+mail["From"]+"] :" + mail["Subject"]
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = mail["From"] + "_hw1answer"
att_path = os.path.join(detach_dir, filename)
if not os.path.isfile(att_path) :
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
The error is showing,
imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED
But, if I use INBOX then it is working.
Working when m.select("inbox")
What is the recommended way to achieve it ?
m.select("important") failed.
If you want the special starred folder, it is probably named "[Gmail]/Important". Use the list() command to find the names used by the server.

python emailing one line at a time

My email program is emailing each line of the message as a separate email, i would like to know how to send all of the message in one email, when the email is sent the program will return to the beginning.
import smtplib
from email.mime.text import MIMEText
a = 1
while a == 1:
print " "
To = raw_input("To: ")
subject = raw_input("subject: ")
input_list = []
print "message: "
while True:
input_str = raw_input(">")
if input_str == "." and input_list[-1] == "":
break
else:
input_list.append(input_str)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
msg['Subject'] = subject
msg['From'] = '123#example.com'
msg['To'] = To
server = smtplib.SMTP_SSL('server', 465)
server.ehlo()
server.set_debuglevel(1)
server.ehlo()
server.login('username', 'password')
# Send a properly formatted MIME message, rather than a raw string
server.sendmail('user#example.net', To, msg.as_string())
server.close()
(the part that takes multiple lines was made with the help Paul Griffiths, Multiline user input python)
for line in input_list:
# Create a MIME text message and populate its values
msg = MIMEText(line)
You are calling server.sendmail in this loop.
Build your entire msg first (in a loop), THEN add all of your headers and send your message.

How do I download only unread attachments from a specific gmail label?

I have a Python script adapted from Downloading MMS emails sent to Gmail using Python
import email, getpass, imaplib, os
detach_dir = '.' # directory where to save attachments (default: current)
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
resp, items = m.search(None, 'FROM', '"Impact Stats Script"') # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
#Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
continue
print "["+mail["From"]+"] :" + mail["Subject"]
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
for part in mail.walk():
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
counter = 1
# if there is no filename, we create one with a counter to avoid duplicates
if not filename:
filename = 'part-%03d%s' % (counter, 'bin')
counter += 1
att_path = os.path.join(detach_dir, filename)
#Check if its already there
if not os.path.isfile(att_path) :
# finally write the stuff
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
I am filtering messages by subject and getting the attachments, but now I need to only get attachments from new emails. Can I modify the m.search() somehow to return only unread emails?
Try modifying this line:
resp, items = m.search(None, 'FROM', '"Impact Stats Script"')
to:
resp, items = m.search(None, 'UNSEEN', 'FROM', '"Impact Stats Script"')
The Python imaplib documentation shows just adding more search criteria, and the IMAP specification defines the UNSEEN search criteria:
UNSEEN
Messages that do not have the \Seen flag set.

Categories

Resources