I am trying to set an autopreply from my outlook, with gpt2 model. I use transformers library. this is my code
import imaplib
import email
from email.mime.text import MIMEText
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import smtplib
import getpass
import string
# Set up IMAP for Outlook email access
outlook_email = '[email protected]'
outlook_password = getpass.getpass(f'Enter the password for {outlook_email}:')
outlook_server = 'outlook.live.com'
outlook_mailbox = 'Inbox'
# Set up GPT-2 model
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
def generate_response(input_text):
input_ids = tokenizer.encode(input_text, return_tensors="pt", max_length=200, truncation=True)
output = model.generate(input_ids, max_length=50, num_return_sequences=1, no_repeat_ngram_size=2)
response = tokenizer.decode(output[0], skip_special_tokens=True)
return response
def send_email(to, subject, message):
from_email = outlook_email
password = outlook_password
msg = MIMEText(message)
msg['To'] = to
msg['From'] = from_email
msg['Subject'] = subject
try:
server = smtplib.SMTP(outlook_server, 587)
server.starttls()
server.login(from_email, password)
server.sendmail(from_email, to, msg.as_string())
server.quit()
print(f"Email sent to {to}")
except Exception as e:
print(f"Error sending email: {e}")
def sanitize_text(input_text):
# Remove non-printable characters
sanitized_text = ''.join(filter(lambda x: x in string.printable, input_text))
return sanitized_text
def process_emails():
# Connect to Outlook email
mail = imaplib.IMAP4_SSL(outlook_server)
mail.login(outlook_email, outlook_password)
mail.select(outlook_mailbox)
# Search for unread emails
result, data = mail.search(None, 'UNSEEN')
email_ids = data[0].split()
for email_id in email_ids:
result, msg_data = mail.fetch(email_id, '(RFC822)')
raw_email = msg_data[0][1]
email_message = email.message_from_bytes(raw_email)
# Extract email content
sender = email_message['From']
subject = email_message['Subject']
body = email_message.get_payload()
# Sanitize the email body
sanitized_body = sanitize_text(body)
# Generate a response using GPT-2
response = generate_response(sanitized_body)
# Send an automated reply
send_email(sender, f"Re: {subject}", response)
# Mark emails as read
for email_id in email_ids:
mail.store(email_id, '+FLAGS', '\Seen')
if __name__ == "__main__":
process_emails()
it sucessfully got into my outlook mail, but there is not email sent for the unread message. Anyone know why ?
I am expecting an email sent automatically if i run this code. I have tried to run it, sucessfuly got into the email but can not send a message to the unread one. I have tried also change the serve to outlook.live.com and outlook.microsoft365.com both doesnt work. my mail domain is outlook.live.com