AIMMS has no built-in function to send email. This article shows how to send an email from your AIMMS
application with the Python-Bridge: the model fills a few string parameters, and a small Python
function sends the email with smtplib from the Python standard library.
This article assumes that the application runs on your own computer, for example in AIMMS Developer. Running it on AIMMS Cloud is not covered.
Note
The Email Client Library (EmailClient, prefix email::) is no longer supported since AIMMS 24.
This article replaces it. See also AIMMS Product Lifecycle.
Prerequisites
AIMMS 25.4 or later, with the Python-Bridge set up as described in Nice to Meet You pyaimms from Python-Bridge: a
pyproject.tomlfile, thepyaimmsrepository library, and thepyaimms_bridge.pyconnection module.An SMTP server that you are allowed to send email through. This can be your company mail server, or an email service that offers an SMTP relay, such as Mailjet, Brevo or SMTP2GO. Several of these services have a free plan for a limited number of emails per day.
The user name and password for that SMTP server. With Mailjet, these are your API key and secret key, and the server is
in-v3.mailjet.comon port 587. Most email services also require you to verify the sender address before you can send.
The example in this article was developed and tested with Mailjet, using its free plan.
smtplib and email are part of the Python standard library, so you don’t need to add a dependency
to pyproject.toml.
To follow along, download the example project (AIMMS 26.8): 413_sending_email.zip.
Before you run it, set the SMTP environment variables described below, and replace the example sender and
recipient addresses with your own.
Storing the SMTP Credentials
Do not put the password in your model or in your Python file. In this example, the Python function reads the SMTP settings from environment variables:
Environment variable |
Example value |
|---|---|
|
|
|
|
|
Your API key, or your mail account |
|
Your secret key, or your mail password |
On Windows, you can set them as user environment variables in . A program only sees environment variables that existed when it started, so close AIMMS completely and start it again after you set or change them.
Steps in the AIMMS Project
Declare string parameters for the email and for the result:
1StringParameter sp_mailFrom;
2StringParameter sp_mailTo;
3StringParameter sp_mailSubject;
4StringParameter sp_mailBodyHtml;
5StringParameter sp_mailAttachment;
6StringParameter sp_mailStatus;
Load the Python file once, for example in PostMainInitialization:
1py::run_python_script("PythonScripts/send_email.py");
To send an email, fill the string parameters and call the Python function:
1sp_mailFrom := "planning@example.com";
2sp_mailTo := "planner@example.com";
3sp_mailSubject := "Optimization results";
4sp_mailBodyHtml := "<p>The new plan is ready.</p>";
5sp_mailAttachment := "Output/plan.xlsx"; ! leave empty for no attachment
6
7py::run_python_statement("send_email()");
8
9if sp_mailStatus <> "OK" then
10 raise error "Sending the email failed: " + sp_mailStatus;
11endif;
To send the email to more than one recipient, separate the addresses in sp_mailTo with commas.
Steps in the Python File
Place send_email.py in the PythonScripts subfolder, next to pyaimms_bridge.py:
1import os
2import smtplib
3from email.message import EmailMessage
4from pathlib import Path
5
6from PythonScripts.pyaimms_bridge import aimms_model
7
8
9def send_email():
10 """Sends the email described by the sp_mail* string parameters in AIMMS."""
11 try:
12 missing = [v for v in ("SMTP_HOST", "SMTP_USER", "SMTP_PASSWORD") if v not in os.environ]
13 if missing:
14 raise RuntimeError("Environment variable(s) not set: " + ", ".join(missing))
15
16 msg = EmailMessage()
17 msg["From"] = aimms_model.sp_mailFrom.data()
18 msg["To"] = aimms_model.sp_mailTo.data()
19 msg["Subject"] = aimms_model.sp_mailSubject.data()
20
21 html = aimms_model.sp_mailBodyHtml.data()
22 msg.set_content("Please view this email in an HTML-capable email client.")
23 msg.add_alternative(html, subtype="html")
24
25 attachment = aimms_model.sp_mailAttachment.data()
26 if attachment:
27 path = Path(attachment)
28 msg.add_attachment(path.read_bytes(), maintype="application",
29 subtype="octet-stream", filename=path.name)
30
31 with smtplib.SMTP(os.environ["SMTP_HOST"], int(os.environ.get("SMTP_PORT", "587"))) as server:
32 server.starttls()
33 server.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
34 server.send_message(msg)
35
36 aimms_model.sp_mailStatus.assign("OK")
37 except Exception as e:
38 aimms_model.sp_mailStatus.assign(str(e))
Remarks:
Lines 12-14: stop with a clear message when the SMTP settings are missing.
Lines 21-23: the email has an HTML body, plus a plain-text fallback for email clients that cannot show HTML.
Lines 25-29: the attachment is optional. Its path is relative to the AIMMS project folder.
Lines 31-34:
starttlsencrypts the connection before the password is sent.Lines 37-38: any error, such as a wrong password or an unknown host, is passed back to AIMMS in
sp_mailStatus.
Alternative: an Email API with the Data Exchange Library
Instead of SMTP, you can also call the REST API of an email service, such as Microsoft Graph (sendMail)
for Microsoft 365, directly from AIMMS with the HTTP client of the Data Exchange library. You then write the email
as a JSON file and send it with a POST request (dex::client::NewRequest with httpMethod: 'POST'
and a requestFile). This keeps everything inside AIMMS, but building the JSON body and attachments takes more work.
For the OAuth2 authorization that Microsoft Graph needs, see Using OAuth2 for API Authorization with DEX.
See also
Python documentation of smtplib and email.message