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

Matlab调用Python邮件发送函数返回值异常,始终获取py.NoneType问题求助

Matlab调用Python邮件发送函数返回值异常,始终获取py.NoneType问题求助

我最近碰到个棘手的问题:在Matlab里调用自己写的Python邮件发送函数时,无论函数执行成功还是遇到特定分支,Matlab里拿到的返回值永远是py.NoneType,但直接用Python运行这个函数却完全正常,返回的字符串都能正确获取。

先给大家看看我的Python代码,是用来通过Gmail SMTP发送带附件的邮件的:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os

def send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path):
    """
    Send an email with an attachment using Gmail's SMTP server.

    Parameters:
    gmail_user (str): Your Gmail email address
    gmail_password (str): Your Gmail app password
    to_email (str): Recipient's email address
    subject (str): Subject of the email
    body (str): Body text of the email
    attachment_path (str): Full path to the attachment file
    """
    try:
        # Create the email
        email = MIMEMultipart()
        email['From'] = gmail_user
        email['To'] = to_email
        email['Subject'] = subject

        # Add the email body
        email.attach(MIMEText(body, 'plain'))

        # Normalize the file path
        attachment_path = attachment_path.encode('utf-8').decode('utf-8')
        attachment_path = os.path.normpath(attachment_path)
       # attachment_path = attachment_path.replace("\\", "\\\\")
        print(f"Processed attachment path: {attachment_path}")

        # Check if the attachment file exists
        if not os.path.exists(attachment_path):
            print(f"Error: The file {attachment_path} does not exist.")
            return 'Name in Email not correct!';
           

        # Open the file in binary mode and encode it
        with open(attachment_path, 'rb') as attachment_file:
            attachment = MIMEBase('application', 'octet-stream')  # Generic MIME type, could be more specific
            attachment.set_payload(attachment_file.read())
            encoders.encode_base64(attachment)

            # Extract filename from the path
            filename = os.path.basename(attachment_path)
            print(f"Attachment found: {filename}")

            # Add header for the attachment
            attachment.add_header('Content-Disposition', 'attachment', filename=filename)

            # Attach the file to the email
            email.attach(attachment)
            print(f"Attachment '{filename}' added successfully.")
            return 'yes'

        # Send the email using Gmail's SMTP server
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls()  # Secure the connection
            server.login(gmail_user, gmail_password)
            server.sendmail(gmail_user, to_email, email.as_string())
            print("Email sent successfully!")
            
            return 'Email sent!'

    except Exception as e:
        print(f"Failed to send email: {e}")
        return 'Email failed fatal!'
    
    return "Unknown error occurred."

我做过的尝试和现状:

  • 写了个简单的Python加法函数(输入两个数返回和),在Matlab里调用能正常拿到返回值,说明Matlab和Python的交互环境是正常的
  • 调用这个邮件函数时,Python里的所有print输出都能在Matlab控制台看到,邮件也确实能成功发送,但就是拿不到返回的字符串
  • 不管是触发路径错误的分支(应该返回Name in Email not correct!),还是正常发送成功(应该返回Email sent!),Matlab里的变量都是py.NoneType
  • Matlab里没有报错信息,Python的异常信息也只有我自己加的print能输出

我在Matlab里的调用方式是:

output=py.send_email.send_email(Arguments)

本来预期output会存储对应的返回字符串,结果完全不符合预期,这真的让我摸不着头脑,有没有大佬能帮我看看问题出在哪?

备注:内容来源于stack exchange,提问作者LLanadas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 14:37:56