Import mail gmail
You want to import emails from Gmail into a Python script. Here's a step-by-step guide to help you achieve this:
Prerequisites:
- You need to have a Gmail account and enable IMAP (Internet Message Access Protocol) in your account settings.
- You need to install the
imaplib
andemail
libraries in your Python environment. You can do this by runningpip install imaplib email
in your terminal.
Code:
import imaplib
import email
import base64
# Gmail account credentials
username = '[email protected]'
password = 'your_password'
# Connect to Gmail IMAP server
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(username, password)
mail.select('inbox')
# Search for all emails in the inbox
status, messages = mail.search(None, 'ALL')
# Iterate through each email
for num in messages[0].split():
status, msg = mail.fetch(num, '(RFC822)')
raw_message = msg[0][1].decode('utf-8')
# Parse the email using the email library
message = email.message_from_string(raw_message)
# Extract the email subject and body
subject = message['Subject']
body = ''
for part in message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True).decode('utf-8')
# Print the email subject and body
print(f"Subject: {subject}")
print(f"Body: {body}")
# Close the IMAP connection
mail.close()
mail.logout()
Note:
- Replace
[email protected]
andyour_password
with your actual Gmail account credentials. - This code imports all emails from the inbox. If you want to import emails from a specific label or folder, you'll need to modify the
search
command accordingly. - The
email
library is used to parse the email messages. Thebase64
library is used to decode the email bodies. - This code prints the email subject and body to the console. You can modify the code to store the emails in a database or file instead.
Security note:
- Be cautious when storing your Gmail account credentials in your Python script. Make sure to use a secure method to store your credentials, such as environment variables or a secure storage service.
- Gmail has a limit on the number of IMAP connections you can make in a short period of time. If you're planning to import a large number of emails, you may need to implement a delay between connections or use a more efficient method to import emails.