import win32com.client as win32
import win32com.client.makepy as makepy
import poplib
from email import parser

makepy.GenerateFromTypeLibSpec("Outlook.Application")

def get_email_body(pop_server, username, password):
    pop_conn = poplib.POP3_SSL(pop_server)
    pop_conn.user(username)
    pop_conn.pass_(password)

    num_messages = len(pop_conn.list()[1])
    if num_messages == 0:
        pop_conn.quit()
        raise Exception("No messages in the mailbox")

    # Assuming we want to read the latest email (index starts from 1)
    latest_email_index = num_messages

    # Retrieve the latest email
    response, msg_lines, octets = pop_conn.retr(latest_email_index)
    message_content = b"\r\n".join(msg_lines).decode('utf-8')

    # Parse the email content
    msg = parser.Parser().parsestr(message_content)
    body = ""
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == 'text/plain':
                body += part.get_payload()
    else:
        body = msg.get_payload()

    pop_conn.quit()
    return body

def mail_gonder_xls():
    outlook = win32.Dispatch("Outlook.Application")
    wsh_shell = win32.Dispatch("WScript.Shell")
    str_desktop = wsh_shell.SpecialFolders("Desktop")

    selection = win32.Dispatch("Excel.Application").Selection
    selection.Copy()

    yeni = win32.Dispatch("Excel.Application").Workbooks.Add()
    yeni.Worksheets(1).Range("A1").PasteSpecial(-4163)  # xlPasteValues constant in Excel

    yeni.SaveAs(str_desktop + "\\Seçilen.xls")

    dam = outlook.CreateItem(0)
    dam.To = "onurturan@hotmail.com"
    dam.Subject = "D.Talepler"
    dam.Body = get_email_body("pop.example.com", "your_username", "your_password")
    dam.Attachments.Add(str_desktop + "\\Seçilen.xls")
    dam.Send()
    
    print("Mail gönderildi.")

if __name__ == "__main__":
    mail_gonder_xls()