有没有办法在没有 Windows 询问“你想如何打开这个文件”的情况下在 python 中发送电子邮件?
Posted
技术标签:
【中文标题】有没有办法在没有 Windows 询问“你想如何打开这个文件”的情况下在 python 中发送电子邮件?【英文标题】:Is there a way to send emails in python without Windows asking you "How you want to open this file"? 【发布时间】:2021-12-31 13:26:08 【问题描述】:我正在设计一种无需支付服务器费用即可拥有在线游戏的方法。为此,我使用以下库:
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 阅读的每封电子邮件打开一个新标签。如果弹出“你想如何打开它”时我没有点击任何东西,我只是继续使用程序,同时让窗口回到后面,它不会打开新标签,程序运行正常.所以我的问题真的是如何防止“如何打开”的存在。
【问题讨论】:
确保您有一个文件扩展名并为每个附件设置一个 Content-Type 标题。具体来说,它可能应该以 .html 结尾并具有 Content-Type: text/html 我有这些文件,但我不知道它们到底是什么意思。 @Max 是webbrowser.open
调用导致对话框出现吗?请注意 webbrowser 文档中的此警告:Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable.
。您至少应该将文件路径转换为 URL。打开file:///….
可能会更好。请注意,现代网络浏览器对基于文件的 HTML 文件施加了很多限制。
太棒了,成功了。 @Max 谢谢!
【参考方案1】:
导致此问题的是 webbrowser.open 行。经过几次测试后,邮件仍然有效,但没有出现额外的选项卡/窗口。
【讨论】:
以上是关于有没有办法在没有 Windows 询问“你想如何打开这个文件”的情况下在 python 中发送电子邮件?的主要内容,如果未能解决你的问题,请参考以下文章
有没有办法重新询问用户获取他的位置的权限,或者使用带有 javascript 的地理定位 API 删除旧设置?