You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python代码发送的Outlook邮件无主题且内容为空?

问题描述

我正在开发一个通过语音输入触发发送邮件的程序,因Gmail不再支持“低安全性应用”,故选用Outlook作为邮件服务。但目前遇到的问题是:发送的所有邮件均无主题且内容为空。以下是我的代码:

#this is my function

def Email(to,subject,content):
    message = EmailMessage()
    message["Subject"] = subject
    message["From"] = "email@outlook.com"
    message["To"] = to
    message.set_content(content)
    server = smtplib.SMTP("smtp-mail.outlook.com", 587)
    server.ehlo()
    server.starttls()
    server.login("email@outlook.com","password")
    server.sendmail("email@outlook.com",to,content)
    server.close()

#AND THIS IS MY FUNCTION CALL
if "send a mail" in query:
    try:
        print("Who do u want to send the mail to?")
        speak("Who do u want to send the mail to?")
        print(mail_dict)
        to = (mail_dict[command()])
        print("what do should I Send?")
        speak("What should I send?")
        subject = "hello from python"
        content = command()
        Email(to,subject,content)
        print("The email was sent.")
        speak("The email was sent.")
    except Exception as e:
        print(e)
        print("sorry! the mail was not sent")
问题原因与解决方法

核心问题

你调用server.sendmail()时传入的是content参数,但该方法需要的是包含主题、发件人、收件人等完整邮件头的标准邮件格式字符串,仅传正文内容会导致邮件结构缺失,出现无主题、内容为空的情况。

修复方案

  1. 修正sendmail参数:将server.sendmail("email@outlook.com",to,content)替换为以下两种方式之一:

    • 使用server.send_message(message):直接传入构建好的EmailMessage对象,SMTP库会自动处理格式转换
    • 使用server.sendmail("email@outlook.com", to, message.as_string()):将EmailMessage对象转为符合邮件标准的字符串
  2. 优化连接管理:用with语句管理SMTP连接,无需手动调用server.close(),连接会自动关闭,避免资源泄漏。

修改后的函数代码

def Email(to, subject, content):
    message = EmailMessage()
    message["Subject"] = subject
    message["From"] = "email@outlook.com"
    message["To"] = to
    message.set_content(content)
    
    with smtplib.SMTP("smtp-mail.outlook.com", 587) as server:
        server.ehlo()
        server.starttls()
        server.login("email@outlook.com", "password")
        server.send_message(message)

额外检查点

确认command()函数是否正确获取语音输入内容,确保content变量被赋值为有效文本,避免因语音识别失败导致内容为空。

内容的提问来源于stack exchange,提问作者Siddharth Dwivedi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 19:22:56