Search code examples
pythonwindowssmtplibimaplib

Is there a way to send emails in python without Windows asking you "How you want to open this file"?


I am designing a way to have an online game without having to pay for a server. To do this I use the following libraries:

import imaplib, smtplib, ssl
import email
from email.header import decode_header
import webbrowser
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

Right now the mailing works and all but whenever I run either the read or write mail commands (shown here:)

    def writeMail(data, fileName = ""):
        username = mail.username
        password = mail.password
        message = MIMEMultipart("alternative")
        if(fileName == ""):
            message["Subject"] = "00302"
        else:
            message["Subject"] = "00302#"+fileName
        message["From"] = username
        message["To"] = username
        text = str(data)
        html = ""
        # Turn these into plain/html MIMEText objects
        part1 = MIMEText(text, "plain")
        part2 = MIMEText(html, "html")
        # Add HTML/plain-text parts to MIMEMultipart message
        # The email client will try to render the last part first
        message.attach(part1)
        message.attach(part2)
    
        # Create secure connection with server and send email
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
            server.login(username, password)
            server.sendmail(username, username, message.as_string())
    
    def clean(text):
        # clean text for creating a folder
        return "".join(c if c.isalnum() else "_" for c in text)
    
    def readMail(fileName = ""):
        username = mail.username
        password = mail.password
        work = False
        # create an IMAP4 class with SSL 
        imap = imaplib.IMAP4_SSL("imap.gmail.com")
        # authenticate
        imap.login(username, password)
        
        status, messages = imap.select("INBOX")
        # total number of emails
        messages = int(messages[0])
        
        for i in range(messages, 0, -1):
            # fetch the email message by ID
            res, msg = imap.fetch(str(i), "(RFC822)")
            for response in msg:
                if isinstance(response, tuple):
                    # parse a bytes email into a message object
                    msg = email.message_from_bytes(response[1])
                    # decode the email subject
                    subject, encoding = decode_header(msg["Subject"])[0]
                    if isinstance(subject, bytes):
                        # if it's a bytes, decode to str
                        subject = subject.decode(encoding)
                    # decode email sender
                    From, encoding = decode_header(msg.get("From"))[0]
                    if isinstance(From, bytes):
                        fFrom = From.decode(encoding)
                    # if the email message is multipart
                    if msg.is_multipart():
                        # iterate over email parts
                        for part in msg.walk():
                            # extract content type of email
                            content_type = part.get_content_type()
                            content_disposition = str(part.get("Content-Disposition"))
                            try:
                                # get the email body
                                body = part.get_payload(decode=True).decode()
                            except:
                                pass
                            if content_type == "text/plain" and "attachment" not in content_disposition:
                                # print text/plain emails and skip attachments
                                mail.body = body
                            if "attachment" in content_disposition:
                                # download attachment
                                filename = part.get_filename()
                                if filename:
                                    folder_name = mail.clean(subject)
                                    if not os.path.isdir(folder_name):
                                        # make a folder for this email (named after the subject)
                                        os.mkdir(folder_name)
                                    filepath = os.path.join(folder_name, filename)
                                    # download attachment and save it
                                    open(filepath, "wb").write(part.get_payload(decode=True))
                    else:
                        # extract content type of email
                        content_type = msg.get_content_type()
                        # get the email body
                        body = msg.get_payload(decode=True).decode()
                        #if content_type == "text/plain":
                        #    # print only text email parts
                        #    print(body)
                    if content_type == "text/html":
                        # if it's HTML, create a new HTML file and open it in browser
                        folder_name = mail.clean(subject)
                        if not os.path.isdir(folder_name):
                            # make a folder for this email (named after the subject)
                            os.mkdir(folder_name)
                        filename = "index.html"
                        filepath = os.path.join(folder_name, filename)
                        # write the file
                        open(filepath, "w").write(body)
                        # open in the default browser
                        webbrowser.open(filepath)
            if(fileName == ""):
                if(subject == "00302"):
                    work = True
                    break
            else:
                if(subject == "00302#"+fileName):
                    work = True
                    break
                
        # close the connection and logout
        imap.close()
        imap.logout()
        if(work):
            return mail.body

At first Windows asked me how I wanted to open a file. When I clicked to open it with Google it started opening a new tab for every email that Python read. If I don't click anything when the "How do you want to open this" pops up, and I just continue to use the program while letting the Window go to the back, it doesn't open new tabs and the program runs normally. So my question really is how to prevent that "How to open" from existing.


Solution

  • It was the line webbrowser.open that was causing this problem. After a couple tests the mailing still works but the extra tabs/windows do not appear.