Python调用系统默认邮件客户端并自动添加附件的方法问询
解决方案
1. Windows系统通用邮件客户端调用(无需Outlook)
通过Python的ctypes调用Windows shell32 API,可调用系统默认邮件客户端并添加附件,支持Thunderbird、Windows Mail等主流客户端:
import ctypes from ctypes import wintypes class SHELLEXECUTEINFO(ctypes.Structure): _fields_ = [ ("cbSize", wintypes.DWORD), ("fMask", wintypes.ULONG), ("hwnd", wintypes.HWND), ("lpVerb", wintypes.LPCSTR), ("lpFile", wintypes.LPCSTR), ("lpParameters", wintypes.LPCSTR), ("lpDirectory", wintypes.LPCSTR), ("nShow", wintypes.INT), ("hInstApp", wintypes.HINSTANCE), ("lpIDList", wintypes.LPVOID), ("lpClass", wintypes.LPCSTR), ("hkeyClass", wintypes.HKEY), ("dwHotKey", wintypes.DWORD), ("hIconOrMonitor", wintypes.HANDLE), ("hProcess", wintypes.HANDLE) ] SEE_MASK_NOCLOSEPROCESS = 0x00000040 SEE_MASK_INVOKEIDLIST = 0x0000000C def send_mail_with_attachment(to, subject, body, attachment_path): shell32 = ctypes.WinDLL("shell32.dll") sei = SHELLEXECUTEINFO() sei.cbSize = ctypes.sizeof(SHELLEXECUTEINFO) sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_INVOKEIDLIST sei.lpVerb = b"open" # 处理含空格的附件路径 attachment = f'"{attachment_path}"' if " " in attachment_path else attachment_path sei.lpFile = b"mailto:" + to.encode('utf-8') sei.lpParameters = f"?subject={subject}&body={body}&attachment={attachment}".encode('utf-8') sei.nShow = 1 # SW_SHOWNORMAL if not shell32.ShellExecuteExA(ctypes.byref(sei)): raise ctypes.WinError() # 使用示例 send_mail_with_attachment( to="recipient@example.com", subject="测试邮件", body="这是测试邮件内容", attachment_path=r"C:\test\file.txt" )
2. 跨平台:调用邮件客户端CLI命令
针对不同客户端的命令行接口直接调用,先检测系统已安装客户端再选择对应方式:
- Thunderbird:
import subprocess import shlex def send_with_thunderbird(to, subject, body, attachment_path): cmd = f'thunderbird -compose "to={to},subject={subject},body={body},attachment={attachment_path}"' subprocess.run(shlex.split(cmd), check=True) - Apple Mail(macOS):
import subprocess import shlex def send_with_apple_mail(to, subject, body, attachment_path): cmd = f'open -a Mail "mailto:{to}?subject={subject}&body={body}&attachment={attachment_path}"' subprocess.run(shlex.split(cmd), check=True)
3. 浏览器引导网页邮件服务(如Gmail)
构造网页邮件的撰写URL,用浏览器打开,用户手动添加附件并输入密码:
import webbrowser import urllib.parse def open_gmail_compose(to, subject, body): params = { 'to': to, 'subject': subject, 'body': body } encoded_params = urllib.parse.urlencode(params) gmail_url = f"https://mail.google.com/mail/u/0/#compose?{encoded_params}" webbrowser.open(gmail_url) # 使用示例 open_gmail_compose( to="recipient@example.com", subject="测试网页邮件", body="这是通过Gmail网页版发送的测试内容" )
4. 第三方库辅助:plyer
跨平台库plyer提供统一接口调用系统默认邮件客户端,支持多平台:
from plyer import email def send_mail_plyer(to, subject, body, attachment_path): email.send( recipient=to, subject=subject, text=body, attachments=[attachment_path] )
内容的提问来源于stack exchange,提问作者JadeCeci
相关产品推荐
相关产品推荐

