calling a python fuction within matlab

1 次查看(过去 30 天)
Hi,
i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab - i always get a py.NoneType as an output.
Here my code in python, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine.
What could the problem be ?
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."
Thanks in advance
I tried a "mini example" with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work.
  4 个评论
Malay Agarwal
Malay Agarwal 2025-1-27
I tried reproducing the issue on my end using MATLAB R2024b but it doesn't seem to be reproducible. Could you tell me which version of MATLAB are you using?
René Lampert
René Lampert 2025-1-27
I use 2024a..finally i solved the problem, the thing was that one has to restart Matlab when the python code gets updated, otherwise Matlab execute the "old" code...it is not a very sufisticated solution but for now it works. Maybe one has to somehow update the python environment within matlab, maybe this could also work

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by