系统邮件编写器发送邮件。
系统邮件撰写:弹出 MessageUI 邮件编辑器,填写收件人、主题、正文与附件。
边界:仅唤起系统邮件界面,用户确认后才发送;不能静默发信。需设备已配置邮件账户(can_send()为True)。
#模块概览
| 项 | 说明 |
|---|---|
| 导入 | import mail |
| 适合做什么 | 分享报告、发送导出文件、反馈邮件 |
| 调用时机 | compose() 放在按钮回调;会弹出全屏编辑器 |
| 推荐顺序 | can_send() → compose(to, subject, body, ...) |
| 返回值 | sent / saved / cancelled / failed |
#快速开始
检查能否发信并撰写一封邮件:
已复制
import mail
if not mail.can_send():
print("未配置邮件账户")
else:
result = mail.compose(
to=["user@example.com"],
subject="Hello",
body="来自 PythonIDE 的测试邮件",
)
print(result)
带附件:
已复制
import mail
attachment = {
"path": "/path/report.pdf",
"mime_type": "application/pdf",
"name": "report.pdf",
}
result = mail.compose(
to="team@example.com",
subject="周报",
body="请查收附件",
attachments=[attachment],
)
#AppUI 示例
撰写邮件放在按钮回调;界面展示最近一次结果。
已复制
import appui
import mail
state = appui.State(
can_send="—",
to="user@example.com",
subject="PythonIDE 演示",
body="这是一封测试邮件。",
result="尚未发送",
)
def refresh_can_send():
state.can_send = "是" if mail.can_send() else "否"
def send_mail():
refresh_can_send()
if state.can_send != "是":
state.result = "未配置邮件账户"
return
result = mail.compose(
to=[state.to],
subject=state.subject,
body=state.body,
)
state.result = result
def body():
return appui.NavigationStack(
appui.Form([
appui.Section("邮件", [
appui.TextField("收件人", text=state.to),
appui.TextField("主题", text=state.subject),
appui.TextEditor(text=state.body).frame(min_height=100),
appui.Button("撰写并发送", action=send_mail)
.button_style("bordered_prominent"),
]),
appui.Section("状态", [
appui.LabeledContent("可发送", value=state.can_send),
appui.LabeledContent("结果", value=state.result),
]),
]).navigation_title("邮件")
)
appui.run(body, state=state)
#API 参考
#速查
| API | 作用 |
|---|---|
can_send() | 是否已配置邮件账户 → bool |
compose(to, subject='', body='', cc=None, bcc=None, attachments=None) | 弹出编辑器 → 结果字符串 |
MailError | 原生能力入口失败异常 |
#compose
compose(...) — 呈现系统 MFMailComposeViewController。
| 参数 | 说明 |
|---|---|
to / cc / bcc | 字符串或列表 |
subject / body | 主题与正文 |
attachments | [{"path", "mime_type", "name"}, ...] |
已复制
result = mail.compose(to=["a@b.com"], subject="Hi", body="...")
# sent | saved | cancelled | failed
#常见错误
| 错误写法 | 后果 | 修正 |
|---|---|---|
未检查 can_send() | 无法弹出编辑器 | 先判断并提示用户配置账户 |
在 body() 里调用 compose | 每次刷新弹邮件窗 | 放进按钮回调 |
| 期望后台自动发信 | 系统不允许 | 用户必须在编辑器中确认发送 |
| 附件路径不存在 | failed | 确认文件在沙盒可访问路径 |
#相关文档
#预期效果
运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。