I am trying to use Outlook to send emails from a specific account.
Users have two or more accounts in their Outlook app and automation needs to use a specific account to send emails from.
To achieve this I used mailItem.SendUsingAccount property as intended per OLE documentation.
Example below.
The problem is when generated email is displayed - FROM field uses CurrentUser account not the one set by SendUsingAccount property.
What am I doing wrong or what am I missing?
procedure TOutlookOLE.AssignSenderFromAccounts(const _MailFromEmail: string);
var
i: integer;
NewSender: OleVariant;
sendermail: string;
report: string;
begin
if Connected then
begin
i := OutlookAppObject.Session.Accounts.Count;
// Cycle through all accounts to identify correct one
for I := 1 to OutlookAppObject.Session.Accounts.Count do
begin
NewSender := OutlookAppObject.Session.Accounts.Item(i);
sendermail := VarToStr(NewSender.SmtpAddress);
// Match accounts based on email address
if NOT VarIsNull(NewSender) AND SameText(sendermail, _MailFromEmail) then
begin
// Match FOUND and set to mail Item ...
// ... but when Displayed THIS IS NOT THE CASE
if MailCreated then
OutlookMailItem.SendUsingAccount := NewSender
else raise Exception.Create('Outlook OLE Exception: Mail object not created.');
break;
end;
end;
end
else raise Exception.Create('Outlook OLE Exception: Outlook not connected.');
end;
Updated WORKING method after Dmitri's reply
procedure TOutlookOLE.AssignSenderFromAccounts(const _MailFromEmail: string);
const PR_SENT_REPRESENTING_EMAIL_ADDRESS = 'http://schemas.microsoft.com/mapi/proptag/0x0065001F';
var
i: integer;
NewSender: OleVariant;
sendermail: string;
report: string;
begin
if Connected then
begin
i := OutlookAppObject.Session.Accounts.Count;
for I := 1 to OutlookAppObject.Session.Accounts.Count do
begin
NewSender := OutlookAppObject.Session.Accounts.Item(i);
sendermail := VarToStr(NewSender.SmtpAddress);
if NOT VarIsNull(NewSender) AND SameText(sendermail, _MailFromEmail) then
begin
if MailCreated then
begin
OutlookMailItem.SendUsingAccount := NewSender;
OutlookMailItem.PropertyAccessor.SetProperty(
PR_SENT_REPRESENTING_EMAIL_ADDRESS,
WideString(_MailFromEmail));
end
else raise Exception.Create('Outlook OLE Exception: Mail object not created.');
break;
end;
end;
end
else raise Exception.Create('Outlook OLE Exception: Outlook not connected.');
end;
It is a known Outlook issue - try to also update the PR_SENT_REPRESENTING_EMAIL_ADDRESS
MAPI property:
OutlookMailItem.PropertyAccessor.SetProperty('http://schemas.microsoft.com/mapi/proptag/0x0065001F', WideString(_MailFromEmail));