Using Outlook (COM) with Matlab: how to set olMailItem.SendUsing property

37 views (last 30 days)
I need to send a mail through Outlook with an address different from the default.
I post here the code I'm using, so that I can explain better the situation
h = actxserver('Outlook.Application'); %Start the server
mail = h.CreateItem('olMailItem'); %Create the mail
mail.SendUsingAccount= h.Session.Accounts.Item(3); %Select the third account
mail.Subject = 'Subject';
mail.BodyFormat = 'olFormatHTML';
mail.HTMLBody = 'Body';
mail.Recipients.Add('address@company.it');
mail.Send(); %Send method
h.release; %Release the server
This code runs without error but if I use the inspector on the variable mail and I check the property SendUsingAccount, it appears that it hasn't been set yet (the get method returns [] before ad after line 3) and the mail is sent by the default account. I also tried
set(mail,'SendUsingAccount',h.Session.Accounts.Item(3))
but it didn't lead me anywhere. As a desperate measure I called .NET libraries (Microsoft.Office.Interop) and run an analogous code through them: it worked like a charm but unfortunately I had huge problems of compatibility with other computers and with the Compiler ( deploytool).
Searching solutions online I noticed that people had a similar problem with VBA but they easily get the job done by using the set method to set the property.
Has anybody faced and solved this problem before?
Thanks
P.S. If I use mail.Display instead of mail.Send() and manually switch the account to the desired one, the property SendUsingAccount becomes editable by Matlab. My guess is that there's a permission problem that it's overridden by the user's intervention.
P.S.2: Matlab r2012a, Microsoft Office 2016

Accepted Answer

Stefano Rognoni
Stefano Rognoni on 20 Oct 2016
Partially solved!
I used a workaround (waaay better than SentOnBehalOfName which is kind of ludicrous): I create the email by replying to an email received by the account that I want to use, i.e.
mail = h.Session.Folders.Item(3).Folders.Item(1).Items.Item(1).Reply
or even
mail = h.Session.Folders.Item('senderaccount@company.it').Folders.Item(1).Items.Item(1).Reply
By replacing this the second line with this and keeping the other lines you should get the result. The only warning is that you must have received 1 email to the sender account.
  2 Comments
Sascha Kühl
Sascha Kühl on 23 Feb 2018
Thanks for sharing your solution, it helped a lot! Just a remark for others to save time: Setting mail.Sender to the desired AddressEntry is also ignored without error.
Mariano
Mariano on 24 Nov 2022
This does not work now (Matlab R2022a, Office365).
Any other suggestion?

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!