I want to send an email via code using Microsoft Visual Basic for Applications. The Microsoft Outlook 12.0 Object Library is checked under Tools/References. The code compiles error-free. The code works fine on two different machines, but when I test it on a third machine, it gives the error when executing line #2.
Dim email As Outlook.MailItem
Set email = Application.CreateItem(olMailItem)
email.To = "myemailaddress@gmail.com"
email.Subject = "Subject"
email.Body = "Body"
email.Send
Set email = Nothing
I have reviewed many posts about this error but cannot find a matching solution. Thanks in advance for your help.
Thanks, everyone, for the intial responses. Turns out what solved the problem is to use CDO for sending the email. Here is the code that worked for me:
Set objMessage = CreateObject("cdo.message")
Set objConfig = CreateObject("cdo.configuration")
Set Flds = objConfig.Fields
Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "myExchangeServerName"
Flds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "myDomain\user@myDomain.com"
Flds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "myPassword"
Flds.Update
Set objMessage.Configuration = objConfig
objMessage.To = "toEmail@someDomain.com"
objMessage.From = "fromEmail@someOtherDomain.com"
objMessage.Subject = "My Subject"
objMessage.Fields.Update
objMessage.HTMLBody = "<p><span style=""font-family: 'Calibri','Arial','sans-serif'"";>My Body Text</span></p>"
objMessage.AddAttachment "C:/path/filename.txt"
objMessage.Send