Python中Windows文件路径问题求助:无法指定邮件附件路径
Hey there! Let's sort out that file path problem you're hitting with your email-sending code—this is such a common gotcha when working with Windows paths in Python, so you’re definitely not alone here.
The Root of the Problem
Windows uses backslashes (\) for file paths, but in Python strings, the backslash acts as an escape character (think \n for newlines, \t for tabs). If you write your path directly like "F:\D\OneDrive\Python\Spyder\test\myfile.txt", Python will misinterpret those backslashes, leading to an invalid path error.
3 Simple Fixes for Your File Path
Here are three easy ways to fix the path so Python reads it correctly:
Use a Raw String
Add anrbefore your path string—this tells Python to treat backslashes as literal characters, no escaping needed:file_path = r"F:\D\OneDrive\Python\Spyder\test\myfile.txt"Double Up the Backslashes
Replace every single backslash with two backslashes (\\). This escapes the escape character, so Python reads it as a literal backslash:file_path = "F:\\D\\OneDrive\\Python\\Spyder\\test\\myfile.txt"Use
pathlib(Recommended for Cross-Platform Code)
Thepathlibmodule makes path handling way cleaner and works seamlessly across Windows, Mac, and Linux. Import it, then define your path like this:from pathlib import Path file_path = Path(r"F:\D\OneDrive\Python\Spyder\test\myfile.txt") # Or even use forward slashes—pathlib will handle it on Windows! # file_path = Path("F:/D/OneDrive/Python/Spyder/test/myfile.txt")
Full Working Code with Attachment
Here’s your code updated with the path fix and complete attachment handling (I filled in the missing parts to make it runnable):
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders from pathlib import Path # Optional, but recommended # Sender and recipient details fromaddr = "your-sender-email@example.com" toaddr = "recipient-email@example.com" # Create the main email message msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Test Email with Attachment" # Add email body body = "Hi there! Attached is the file you requested." msg.attach(MIMEText(body, 'plain')) # --- Fix the file path here --- file_path = r"F:\D\OneDrive\Python\Spyder\test\myfile.txt" # Or use pathlib: file_path = Path(r"F:\D\OneDrive\Python\Spyder\test\myfile.txt") # Attach the file try: with open(file_path, "rb") as attachment: # Create a MIMEBase object to hold the attachment part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) # Encode the attachment in base64 encoders.encode_base64(part) # Set the attachment header with the filename part.add_header('Content-Disposition', f'attachment; filename="myfile.txt"') # Add the attachment to the email msg.attach(part) except FileNotFoundError: print(f"Error: Could not find file at {file_path}") exit() # Send the email (example using Gmail; adjust for your email provider) try: # Connect to SMTP server server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() # Enable TLS encryption server.login(fromaddr, "your-app-password-or-email-password") # Use app password for 2FA-enabled accounts # Convert message to string and send text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {str(e)}")
Quick Notes to Avoid Other Issues
- Double-check that the file path is exact—even a tiny typo (like a missing folder name) will cause a
FileNotFoundError. - If you’re using Gmail with two-factor authentication enabled, you’ll need to use an app password instead of your regular email password.
- For other email providers (Outlook, Yahoo, etc.), adjust the SMTP server address and port (e.g., Outlook uses
smtp.office365.comon port 587).
内容的提问来源于stack exchange,提问作者Mark Carr




