Hello,
I'm trying to send Outlook email through .NET API. Any help on coding would be highly appreciated. Below is the "known" code by using COM and actxserver, but as I'm facing some other issues, I'd like to see if I can fix that probelm by switching to .NET.
function sendolmail(to,subject,body,attachments)
%Sends email using MS Outlook. The format of the function is
%Similar to the SENDMAIL command.
% Create object and set parameters.
h = actxserver('outlook.Application');
mail = h.CreateItem('olMail');
mail.Subject = subject;
mail.To = to;
mail.BodyFormat = 'olFormatHTML';
mail.HTMLBody = body;
% Add attachments, if specified.
if nargin == 4
for i = 1:length(attachments)
mail.attachments.Add(attachments{i});
end
end
% Send message and release object.
mail.Send;
h.release;
Here's how far I'm at the momment :)
dotnetenv("framework")
h=NET.addAssembly('microsoft.office.interop.outlook');
Now I'd need to dublicate the rest of the code, which I haven't succeeded in yet.
Here's a link to Microsoft's namespace for Outlook.
Thanks in advance,
Tero

 Réponse acceptée

Aditya Singh
Aditya Singh le 6 Juil 2023
Modifié(e) : Aditya Singh le 6 Juil 2023
Hi Tero,
To my understanding you want to send mail using the .NET API and outlook.
Using the actxserver and the oulook API, its simple to send mail. While for .NET, you have to create your acces token and send in the file header. You can refer to Get Started with the Outlook REST APIs - Outlook Developer | Microsoft Learn for generating access token.
NET.addAssembly('System');
NET.addAssembly('System.Net.Http');
NET.addAssembly('System.Net.Http.Headers');
NET.addAssembly('System.Text');
% Create the HttpClient object
client = System.Net.Http.HttpClient();
% Set the access token
accessToken = '<Your_Access_Token>';
client.DefaultRequestHeaders.Authorization = System.Net.Http.Headers.AuthenticationHeaderValue('Bearer', accessToken);
% Set the email endpoint
emailEndpoint = 'https://graph.microsoft.com/v1.0/me/sendMail';
% Set the email content
emailBody = 'Hello, this is the email body.';
recipientEmail = 'recipient@example.com';
emailSubject = 'Test Email';
% Create the JSON payload
jsonPayload = sprintf('{"message": {"subject": "%s", "body": {"contentType": "Text", "content": "%s"}, "toRecipients": [{"emailAddress": {"address": "%s"}}]}}', emailSubject, emailBody, recipientEmail);
% Create the StringContent object
content = System.Net.Http.StringContent(jsonPayload, System.Text.Encoding.UTF8, 'application/json');
% Send the POST request to send the email
response = client.PostAsync(emailEndpoint, content).Result;
if response.IsSuccessStatusCode
disp('Email sent successfully.');
else
disp(['Failed to send email. Error: ' char(response.ReasonPhrase.ToString)]);
end
This should work, if you can tell your issues with the COM and actxserver we can try to resolve them.
For more information you can refer to
Hope it helps!

5 commentaires

Tero
Tero le 6 Juil 2023
Thank you! I will go this through.
The reason why I'm investigating .NET is a bit more complex. I have a small standalone .exe on a remote computer, which is sending a file by email (here I'm using the sendolmail function, which is working fine in normal conditions). Running this executable is performed through a .bat file, which, in turn, is activated through Windows Task Scheduler, when an ssh command is sent to this remote computer to start the task, simple :)
However, when a user is not logged on to this computer, I would select the task to "run whether user is logged in or not". This will start the .exe, but it seems the email sending function is stopped on the actxserver line in the code.
So I don't know will the use of .NET will fix this, but I will try.
Aditya Singh
Aditya Singh le 6 Juil 2023
The reason for it to "stop" when the user is not logged in to that device is because actxserver and COM uses the Outlook (fully setup) present on that device to send the mail. I also encountered this once when I was trying to run the code from my VDI machine which did not had Outlook.
I believe since the .NET implementation is using an acess token, the "not logged in" user won't be a problem.
Hope it helps!
Tero
Tero le 6 Juil 2023
Perfect, my confidence level just went up!!
Tero
Tero le 6 Juil 2023
btw, could I ask your assistance on adding an attachment file. This seems not to be present on the code of yours
Aditya Singh
Aditya Singh le 6 Juil 2023
Modifié(e) : Aditya Singh le 6 Juil 2023
Hi,
All the changes with the mail body and attachments can be made in the jsonPayload, you can refer to
and for large files:
The JSON of the resource would be would be updated as
{
"contentType": "string",
"id": "string (identifier)",
"isInline": true,
"lastModifiedDateTime": "String (timestamp)",
"name": "string",
"size": 1024
}
Hope it helps!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by