1
votes

I am using PHP and outlook to send email. I have multiple accounts set up in outlook, and I want to send email from a particular account each time. My current code looks like:

if (!defined('olMailItem')) define("olMailItem",0);
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$myItem->To= '[email protected]';
$myItem->SentOnBehalfOfName = '[email protected]';
$myItem->Subject='my subject';

$myItem->HTMLBody='email content';
$myItem->Display();
$myItem->Send()

using $myItem->SentOnBehalfOfName doesn't works, it always sends email using default account, but I want to set the from account using PHP.

1

1 Answers

1
votes

It looks like you are interested in the SendUsingAccount property of the MailItem class which allows to set an Account object that represents the account under which the MailItem is to be sent. The SendUsingAccount property can be used to specify the account that should be used to send the MailItem when the Send method is called. For example:

Sub SendUsingAccount() 
  Dim oAccount As Outlook.account 
  For Each oAccount In Application.Session.Accounts 
    If oAccount.AccountType = olPop3 Then 
      Dim oMail As Outlook.MailItem 
      Set oMail = Application.CreateItem(olMailItem) 
      oMail.Subject = "Sent using POP3 Account" 
      oMail.Recipients.Add ("[email protected]") 
      oMail.Recipients.ResolveAll 
      oMail.SendUsingAccount = oAccount 
      oMail.Send 
    End If 
  Next 
End Sub 

Be aware, Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. See Considerations for server-side Automation of Office for more information.