簡體   English   中英

有沒有辦法在 python 中發送電子郵件而 Windows 詢問您“您想如何打開此文件”?

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

我正在設計一種無需支付服務器費用即可擁有在線游戲的方法。 為此,我使用以下庫:

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

現在郵件工作正常,除了我運行讀或寫郵件命令(顯示在這里:)

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

一開始Windows問我想怎么打開一個文件。 當我點擊用谷歌打開它時,它開始為 Python 讀取的每個 email 打開一個新標簽。 如果彈出“你想如何打開這個”時我不點擊任何東西,我只是繼續使用程序,同時讓 Window go 到后面,它不會打開新標簽,程序運行正常. 所以我的問題實際上是如何防止“如何打開”的存在。

導致此問題的是 webbrowser.open 行。 經過幾次測試后,郵件仍然有效,但不會出現額外的選項卡/窗口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM