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, 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.
No errors are showing up in Matlab and also no details from the python code.
My expectation was that when calling the function from Matlab like output=py.send_email.send_email(Arguments)
The variable "output" holds the string 'Email sent!', but instead is always py.NoneType.
I built in some print statement just to check if Matlab prints it properly, and it does ! The email is being sent as it should. I just want an output variable for some extra coding in Matlab. I also get no return when i use the wrong path where I should get 'Name in Email not correct!', and this is just at the beginning.
I solved the problem by a simple restart of matlab, I was not aware of this apparently simple "issue". So when changing the python code one has to restart matlab to execute the updated python code. Maybe an other solution would be to somehow terminate and reboot the python environment in matlab.