region:us
import imaplib
import email
from transformers import BartForConditionalGeneration, BartTokenizer, pipeline

# Load pre-trained model and tokenizer for summarization
model_name = 'facebook/bart-large-cnn'
tokenizer = BartTokenizer.from_pretrained(model_name)
model = BartForConditionalGeneration.from_pretrained(model_name)

# Load sentiment analysis model
sentiment_analyzer = pipeline('sentiment-analysis', model='distilbert-base-uncased')

# Connect to your email account
mail = imaplib.IMAP4_SSL('imap.gmail.com')  # Example for Gmail, adjust accordingly
mail.login('your_email@gmail.com', 'your_password')
mail.select('inbox')  # Select the mailbox you want to retrieve emails from

# Function to generate summary
def generate_summary(email_text):
    inputs = tokenizer([email_text], return_tensors='pt', max_length=1024, truncation=True)

    with torch.no_grad():
        summary_ids = model.generate(**inputs)

    summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
    return summary

# Search for all emails
status, messages = mail.search(None, 'ALL')
message_ids = messages[0].split()

# Process and summarize the latest 10 emails received today
for msg_id in message_ids[-10:]:
    status, msg_data = mail.fetch(msg_id, '(RFC822)')
    raw_email = msg_data[0][1]
    msg = email.message_from_bytes(raw_email)
    sender = msg['From']
    subject = msg['subject']
    body = ""

    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == "text/plain":
                body = part.get_payload(decode=True).decode()
                break
    else:
        body = msg.get_payload(decode=True).decode()

    if body:
        summary = generate_summary(body)

        # Perform sentiment analysis on the summary
        sentiment_result = sentiment_analyzer(summary)
        label = sentiment_result[0]['label']
        score = sentiment_result[0]['score']

        print(f"From: {sender}")
        print(f"Email Subject: {subject}")
        print(f"Generated Summary: {summary}")
        print(f"Sentiment: {label}, Score: {score}")
        print("-" * 50)

mail.logout()