-
-
Save robulouski/7441883 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python | |
# | |
# Very basic example of using Python and IMAP to iterate over emails in a | |
# gmail folder/label. This code is released into the public domain. | |
# | |
# RKI July 2013 | |
# http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/ | |
# | |
import sys | |
import imaplib | |
import getpass | |
import email | |
import email.header | |
import datetime | |
EMAIL_ACCOUNT = "[email protected]" | |
EMAIL_FOLDER = "Top Secret/PRISM Documents" | |
def process_mailbox(M): | |
""" | |
Do something with emails messages in the folder. | |
For the sake of this example, print some headers. | |
""" | |
rv, data = M.search(None, "ALL") | |
if rv != 'OK': | |
print "No messages found!" | |
return | |
for num in data[0].split(): | |
rv, data = M.fetch(num, '(RFC822)') | |
if rv != 'OK': | |
print "ERROR getting message", num | |
return | |
msg = email.message_from_string(data[0][1]) | |
decode = email.header.decode_header(msg['Subject'])[0] | |
subject = unicode(decode[0]) | |
print 'Message %s: %s' % (num, subject) | |
print 'Raw Date:', msg['Date'] | |
# Now convert to local date-time | |
date_tuple = email.utils.parsedate_tz(msg['Date']) | |
if date_tuple: | |
local_date = datetime.datetime.fromtimestamp( | |
email.utils.mktime_tz(date_tuple)) | |
print "Local Date:", \ | |
local_date.strftime("%a, %d %b %Y %H:%M:%S") | |
M = imaplib.IMAP4_SSL('imap.gmail.com') | |
try: | |
rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass()) | |
except imaplib.IMAP4.error: | |
print "LOGIN FAILED!!! " | |
sys.exit(1) | |
print rv, data | |
rv, mailboxes = M.list() | |
if rv == 'OK': | |
print "Mailboxes:" | |
print mailboxes | |
rv, data = M.select(EMAIL_FOLDER) | |
if rv == 'OK': | |
print "Processing mailbox...\n" | |
process_mailbox(M) | |
M.close() | |
else: | |
print "ERROR: Unable to open mailbox ", rv | |
M.logout() | |
#!/usr/bin/env python | |
# | |
# Very basic example of using Python 3 and IMAP to iterate over emails in a | |
# gmail folder/label. This code is released into the public domain. | |
# | |
# This script is example code from this blog post: | |
# http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/ | |
# | |
# This is an updated version of the original -- modified to work with Python 3.4. | |
# | |
import sys | |
import imaplib | |
import getpass | |
import email | |
import email.header | |
import datetime | |
EMAIL_ACCOUNT = "[email protected]" | |
# Use 'INBOX' to read inbox. Note that whatever folder is specified, | |
# after successfully running this script all emails in that folder | |
# will be marked as read. | |
EMAIL_FOLDER = "Top Secret/PRISM Documents" | |
def process_mailbox(M): | |
""" | |
Do something with emails messages in the folder. | |
For the sake of this example, print some headers. | |
""" | |
rv, data = M.search(None, "ALL") | |
if rv != 'OK': | |
print("No messages found!") | |
return | |
for num in data[0].split(): | |
rv, data = M.fetch(num, '(RFC822)') | |
if rv != 'OK': | |
print("ERROR getting message", num) | |
return | |
msg = email.message_from_bytes(data[0][1]) | |
hdr = email.header.make_header(email.header.decode_header(msg['Subject'])) | |
subject = str(hdr) | |
print('Message %s: %s' % (num, subject)) | |
print('Raw Date:', msg['Date']) | |
# Now convert to local date-time | |
date_tuple = email.utils.parsedate_tz(msg['Date']) | |
if date_tuple: | |
local_date = datetime.datetime.fromtimestamp( | |
email.utils.mktime_tz(date_tuple)) | |
print ("Local Date:", \ | |
local_date.strftime("%a, %d %b %Y %H:%M:%S")) | |
M = imaplib.IMAP4_SSL('imap.gmail.com') | |
try: | |
rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass()) | |
except imaplib.IMAP4.error: | |
print ("LOGIN FAILED!!! ") | |
sys.exit(1) | |
print(rv, data) | |
rv, mailboxes = M.list() | |
if rv == 'OK': | |
print("Mailboxes:") | |
print(mailboxes) | |
rv, data = M.select(EMAIL_FOLDER) | |
if rv == 'OK': | |
print("Processing mailbox...\n") | |
process_mailbox(M) | |
M.close() | |
else: | |
print("ERROR: Unable to open mailbox ", rv) | |
M.logout() |
For two-way verification the best and recommended solution is to generate an app password https://security.google.com/settings/security/apppasswords.
def process_mailbox (M )
What is the parameter (M ) ? You get what ?
Sorry and discomfort
Thank you!
James-Dias 'M' here is the IMAP4 Instance which is passed to process_mailbox().
body can be obtained by msg.get_payload()
nice code, it helps me to understand a lot about email handling, but is there any way to extract the attachments in the email separately or to save a message in as a file.
I have written Python code that downloads the attachments and also generate an excel fie as log which has the hyperlink to the attachments.
Take a look at my blog
thanks for getting me started with imaplib
Hello! How can I get decoded content?
content = str(email.header.make_header(email.header.decode_header(str(msg.get_payload()[0]))))
It returns encoded string :(
line 71 of gmail_imap_python3.py could easily be changed to use pprint instead of print for easier reading 👍
pprint.pprint(mailboxes)
Remember to import pprint
Thanks so much for this!
Thanks a lot bro its worked me bro... now i want to read an attachement file from gmail is above code is similar to that one or not..?
Thanks for the code. Is there a way to read or download an attachment ? I have been looking for it from 2 days, but didn't find any. Can someone help me plz.
Thank You
Nice code i used to save my mail in html file addin this few lines after "print('Raw Date:', msg['Date'])"
content = str(msg.get_payload())
#cleaning the file name
filename_split = subject.replace(':','-').split(' de ')
# if file name is correct
if len(filename_split):
# building the file name
filename = filename_split[1]+filename_split[0]+'.html'
#create the html file with the rigth encoding
f=open(filename,'w',encoding='iso-8859-1')
f.write(content)
f.close
thank you all
I have tried the above code but it is throwing the below error.
[ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)
Please help
@sree-cgit, login to your google account, click this link https://myaccount.google.com/security , on the page scroll to the bottom of the page and turn ON "Allow less secure Apps"
Then also make sure you are correctly supplying your login details
@robulouski
:)..thanks , this helped me get started with email on python.
Hello! How can I get decoded content?
content = str(email.header.make_header(email.header.decode_header(str(msg.get_payload()[0]))))
It returns encoded string :(
Decode with:
data.decode("utf-8")
I could not run the code with my yahoo mail account?
How can I convert it to yahoo?
Thanks
Can you try this code?
It works for Gmail and Yahoo
https://gist.github.com/PandaWhoCodes/f7adce3bff9bb1f508b3ab42db05a6bf
Can someone please let me know how to search gmail messages that are grouped. So, let's say I have 1000 emails and are grouped to send 100 email messages in one email, so we will see 10 emails for 1000 email messages. How to retrieve the grouped emails like this ?
Hi..
Is there anyway we can parse data if the body of the email is an html content?
How do we pass this information to this code?
Absolutely splendid! Thanks a lot for this mate.
Do you happen to have a snippet to send SMTP mails in Python3 as well? Cheers!
@pizzabreath Check out this snippet from Real Python for Gmail with getpass
added on my end (vs. input
):
from getpass import getpass
import smtplib
import ssl
port = 465 # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "[email protected]" # Enter your address
receiver_email = "[email protected]" # Enter receiver address
password = getpass("Type your password and press enter: ")
message = """\
Subject: Hi there
This message is sent from Python."""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
I was getting the login failed message, even without two-way verification, until I enabled access from less secure maps in the Gmail settings. Thank you @hollerith for mentioning this https://www.google.com/settings/security/lesssecureapps