Outlook 2007 & E-mails (1 Viewer)

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
I am using the following code which I found on this site to generate e-mails from within my application. It works fine except a creates another session of Outlook everytime I call the routine even if I already have Outlook running. I'm using Access 2007 and Oitlook 2007.

Code:
Public Function SendMessage(varTo As Variant, strSubject As String, strBody As String, _
     bolAutoSend As Boolean, bolSaveInOutbox As Boolean, bolAddSignature As Boolean, _
    Optional varCC As Variant, Optional varBCC As Variant, Optional varReplyTo As Variant, Optional varAttachmentPath As Variant, Optional varImagePath As Variant, Optional varHtmlFooter As Variant) As Boolean
'=================================================================
'
'varto: a string of email addresses, multiples delimted by semi-colon
'strSubject: subject line for the email
'strBody: body of the email, must be wrapped in <html> </html> tags, and optionally any other formatting tags
'bolAutoSend: determines whether email is sent automatically or displayed to the user
'bolSaveInOutbox: determines if the message is saved in the outbox
'boladdsignature: determines if the user's default signature is added to the outgoing email
'varCC: (Optional) CC email addresses, multiples delimited by semi-colon
'varBCC: (Optional) BCC email addresses, multiples delimited by semi-colon
'varReplyTo (Optional) If specified sets the reply to email address, multiples delimited by semi-colon
'varAttachmentPath: (Optional) If specified attaches the file
'varImagePath: (Optional) If specified embeds the image in the body of the email
'varHtmlFooter: (Optional) If specifed, inserts an html file as a footer to the message.
'ASSUMPTIONS: Outlook, HTML message format, Word is the default editor
'When performing some of the optional steps the message is constructed in the following order
'signature then embedded image then footer then body text, so the actual email would read as follows
'body text, footer, embedded image, signature
'=================================================================
On Error GoTo HandleError
Dim i As Integer
Dim strtempfile As String
Dim strmsg As String
Dim objOutlook As Outlook.Application
Dim objNameSpace As Outlook.Namespace
Dim objInbox As Outlook.MAPIFolder
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim objInsp As Outlook.Inspector
Dim objword As Word.Application
Dim objdoc As Word.Document
Dim objrange As Word.Range
SendMessage = False
Set objOutlook = New Outlook.Application                                'Create the Outlook session.
objOutlook.Session.Logon
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)                   'Create the message.
Set objNameSpace = objOutlook.GetNamespace("MAPI")                       'Set MAPI Mail
Set objInbox = objNameSpace.GetDefaultFolder(olFolderInbox)               'Set Inbox
objInbox.Display                                                         'Make Outlook visible
strBody = ReplaceCRLFwithBR(strBody)                                    'Replace any vbcrlf with <br>
If (InStr(strBody, "<font") = 0) Or (InStr(strBody, "<html>") = 0) Then                              'if no <html> and <font> tags then wrap the body of the message with these tags
    strBody = FormatAsHtml(strBody)
End If
With objOutlookMsg
 
    If Not IsMissing(varTo) Then
        If varTo <> "" And Not IsNull(varTo) Then
            For i = 1 To CountCSWords(varTo)
                Set objOutlookRecip = .Recipients.Add(GetCSWord(varTo, i))               'Add the TO recipient(s) to the message.
                objOutlookRecip.Type = olTo
            Next i
        End If
    End If
    If Not IsMissing(varCC) Then
        If varCC <> "" And Not IsNull(varCC) Then
            For i = 1 To CountCSWords(varCC)
                Set objOutlookRecip = .Recipients.Add(GetCSWord(varCC, i))                  'Add the cc recipient(s) to the message.
                objOutlookRecip.Type = olCC
            Next i
        End If
    End If
 
    If Not IsMissing(varBCC) Then
        If varBCC <> "" And Not IsNull(varBCC) Then
            For i = 1 To CountCSWords(varBCC)
                Set objOutlookRecip = .Recipients.Add(GetCSWord(varBCC, i))                 'Add the bcc recipient(s) to the message.
                objOutlookRecip.Type = olBCC
            Next i
        End If
    End If
 
    If Not IsMissing(varReplyTo) Then
        If varReplyTo <> "" And Not IsNull(varReplyTo) Then
            For i = 1 To CountCSWords(varReplyTo)
                Set objOutlookRecip = .ReplyRecipients.Add(GetCSWord(varReplyTo, i))        'Add the bcc recipient(s) to the message.
            Next i
        End If
    End If
 
 
    If (Not IsMissing(varAttachmentPath)) Then                                                      'if attachment is specified
        If (varAttachmentPath <> "") And (Not IsNull(varAttachmentPath)) Then                       'check it is valid
            If Dir(varAttachmentPath, vbHidden + vbSystem + vbReadOnly + vbDirectory) <> "" Then    'check the file actually exists
                Set objOutlookAttach = .Attachments.Add(CStr(varAttachmentPath))                      'Add attachments to the message.
            End If
        End If
    End If
 
 
    .Subject = strSubject               'Set the Subject of the message.
    .BodyFormat = olFormatHTML          'set format to html
 
    If bolAddSignature Or Not IsMissing(varImagePath) Or Not IsMissing(varHtmlFooter) Then  'if signature or embedded image or html footer
        Set objInsp = objOutlookMsg.GetInspector                                            'this causes the default signature to be added to the message
        Set objdoc = objInsp.WordEditor
        If objdoc Is Nothing Then
            strmsg = "Outlook must use Word as the email editor. Follow these instructions to fix the problem." & vbCrLf & vbCrLf & _
                "Tools>Options" & vbCrLf & "Then select 'Mail Format' tab" & vbCrLf & "Ensure Use Microsoft Office Word 2003 to edit e-mail messages."
            MsgBox strmsg
            objOutlookMsg.Close olDiscard
            GoTo SendMessage_Done
        End If
 
        Set objword = objdoc.Application
 
        If bolAddSignature = False Then         'If the user had a signature it would have been applied, if we dont want it then we need to delete it here
            objdoc.Range.Delete
        End If
 
        If Not IsMissing(varImagePath) Then
            If varImagePath <> "" And Not IsNull(varImagePath) Then
                If Dir(varImagePath, vbHidden + vbSystem + vbReadOnly + vbDirectory) <> "" Then
                    On Error Resume Next
                    .Display                                                                        'Seems like word document must be visible before you can use addpicture method
                    If Err <> 0 Then            'if the mail cound not be displayed then display a warning and discard the message
                        MsgBox "It was not possible to display the message, check that there are no dialog boxes open in Outlook." & vbCrLf & "Please close all Outlook windows and emails, and then attempt this update again.", vbCritical
                        .Close olDiscard
                        GoTo SendMessage_Done
                    End If
                    objword.WindowState = wdWindowStateMinimize                                     'minimize word application so user does not see mail being created
                    Set objrange = objdoc.Range(Start:=0, End:=0)                                   'goto start of message again
                    objrange.InsertBefore vbCrLf
                    objdoc.InlineShapes.AddPicture Filename:=varImagePath, LinkToFile:=False, SaveWithDocument:=True, Range:=objrange
                End If
            End If
        End If
        If Not IsMissing(varHtmlFooter) Then
            If varHtmlFooter <> "" And Not IsNull(varHtmlFooter) Then
                If Dir(varHtmlFooter, vbHidden + vbSystem + vbReadOnly + vbDirectory) <> "" Then
                    Set objrange = objdoc.Range(Start:=0, End:=0)                                   'goto start of message
                    objrange.InsertFile varHtmlFooter, , , False, False   'insert the html from the external file
                End If
            End If
        End If
 
        strtempfile = Environ("temp") & Format(Now(), "yyyymmddhhnnss") & ".htm"        'generate temp filename
        Set objrange = objdoc.Range(Start:=0, End:=0)                                   'goto start of message again
        CreateTextFile strtempfile, strBody                                             'save the bodytext as a temporary htm file
        objrange.InsertFile strtempfile, , , False, False                               'insert the htm file into the body of the message
        Kill strtempfile                                                                'delete temp file
 
        objdoc.SpellingChecked = True                                                   'doesnt matter for autosend, but helps the user if the message is being displayed
    Else
        .HTMLBody = strBody
    End If
 
    If bolSaveInOutbox = False Then             'if message not to be saved after sending
        .DeleteAfterSubmit = True               'specify that it should be deleted
    End If
 
    If (bolAutoSend = True) And (.Recipients.Count > 0) Then        'check that there is at least 1 recipient before trying to autosend
        .Send
    Else
        Err = 0
        On Error Resume Next
        .Display                    'Attempt to display the message
        If Err <> 0 Then            'if the mail cound not be displayed then display a warning and discard the message
            MsgBox "It was not possible to display the message, check that there are no dialog boxes open in Outlook." & vbCrLf & "Please close all Outlook windows and emails, and then attempt this update again.", vbCritical
            .Close olDiscard
            GoTo SendMessage_Done
        End If
    End If
End With
 
SendMessage = True
SendMessage_Done:
    Set objOutlook = Nothing
    Set objNameSpace = Nothing
    Set objInbox = Nothing
    Set objOutlookMsg = Nothing
    Set objOutlookRecip = Nothing
    Set objOutlookAttach = Nothing
    Set objInsp = Nothing
    Set objword = Nothing
    Set objdoc = Nothing
    Set objrange = Nothing
    Exit Function
HandleError:
    MsgBox Err.Number & ":" & Err.Description, vbCritical
    Resume SendMessage_Done
End Function
Public Function ReplaceCRLFwithBR(ByVal strText) As String
'=================================================================
'Replace all vbcrlf with <br> to keep line breaks in html emails
'=================================================================
strText = Replace(strText, Chr(13), "<br>")
strText = Replace(strText, Chr(10), "")
ReplaceCRLFwithBR = strText
 
End Function
Public Function FormatAsHtml(ByVal str) As String
'=================================================================
'Wraps a string in html tags
'=================================================================
FormatAsHtml = "<html><font face=""arial"" size=""2"">" & str & "</font></html>"
End Function
Public Function GetCSWord(ByVal str, Indx As Integer, Optional strdelimiter = ";") As String
'=================================================================
'Returns the nth word in a specific field
'=================================================================
On Error Resume Next
GetCSWord = Split(str, strdelimiter)(Indx - 1)
End Function
Function CountCSWords(ByVal str, Optional strdelimiter = ";") As Integer
'=================================================================
'Counts the words in the delimited string
'=================================================================
Dim WC As Integer, Pos As Integer
If VarType(str) <> 8 Or Len(str) = 0 Then
    CountCSWords = 0
    Exit Function
End If
WC = 1
Pos = InStr(str, strdelimiter)
Do While Pos > 0
    WC = WC + 1
    Pos = InStr(Pos + 1, str, strdelimiter)
Loop
CountCSWords = WC
 
End Function
 
Public Sub CreateTextFile(strFullPath As String, strText As String)
'=================================================================
'Creates a text file with the specified file name containing the supplied text
'=================================================================
Dim fso As Object
Dim MyFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(strFullPath, True)          'Creates file, existing file will be overwritten
MyFile.WriteLine (strText)                                  'writes string to the file
MyFile.Close                                                'close the file
 
End Sub
Public Function GetTextFile(ByVal strFile As String) As String
'=================================================================
'Returns a string that contains the contents of the specified file
'=================================================================
 
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(strFile).OpenAsTextStream(1, -2)       'Open the file ForReading, Use system default for file format
GetTextFile = ts.readall                                    'Read the contents of the file
ts.Close                                                    'Close the file
 
End Function
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
Set objOutlook = New Outlook.Application 'Create the Outlook session.
[/code]

The reason for what you are seeing has to do with this line here. Your code simply starts a new outlook session.

There are a couple of ways to do this. I prefer the following;
Code:
On Error Resume Next
bln_QuitOutlook = False
Set olApp = GetObject(, "Outlook.Application")

If Err.Number = 429 Then
    Set olApp = New Outlook.Application
    bln_QuitOutlook = True
Err.Clear
End If
This code will attempt to first get an already open outlook. If outlook is not open then there will be an error no. 429. This is captured which then opens a NEW outlook.

If it is important that outlook closes again then use the "bln_QuitOutlook" as a boolean setting it to true if you have to open outlook.

Then once you are finished with your outlook session quit outlook. Make sure you set all outlook objects to NOTHING and also make sure that the last object you set to NOTHING is the Outlook.Application (objOutlook) object. If you do not do it this way it will most likely remain running.
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
Thanks I tried that but I get an error further down the routine :-

Code:
Set objdoc = objInsp.WordEditor
        If objdoc Is Nothing Then
           strmsg = "Outlook must use Word as the email editor. Follow these instructions to fix the problem." & vbCrLf & vbCrLf & _
              "Tools>Options" & vbCrLf & "Then select 'Mail Format' tab" & vbCrLf & "Ensure Use Microsoft Office Word 2003 to edit e-mail messages."
               MsgBox strmsg
             objOutlookMsg.Close olDiscard
            GoTo SendMessage_Done
        End If

I'm using Outlook 2007 which always uses Word as an Editor !!!
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
What is the error you get and on what line does it show this error.

Or do you actually get the error message that you have shown?

1. Have you done what is suggested there?
2. I do not know if O2007 must be visible to use Word as the editor you could always just make O2007 visible to test.
3. You do not need to use word as the editor for emails. Emails can be normal text or can be written in HTML. What is your reason for useing Word?

One further thought
Code:
Set objInsp = objOutlookMsg.GetInspector
Maybe this line is failing as Inspector which is the window you see when you click new mail is not visible and thus is not getting an object.

Do you know how to step through your code and check it with F8?
Check if you are getting an inspector object. If not then make the inspector (in other words this email) visible.
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
Ran the code with F8
objdoc and objInsp both set to Nothing.

What do they need to be set to ???
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
Can you show me how your code now looks and can you give me an example of your call for the function please.

I will set it up and test.
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
I attach a cut-down version of my Access 2007 Database.

I have put your amended code within it.

If you call up the Form 'Quotations List' then select a record, one of the buttons on the top calls a routine to 'e-mail the quotation'

As mentioned previously I use Outlook 2007

Good Luck
 

Attachments

  • TestDatabase.accdb
    832 KB · Views: 302

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
Hi wllsth,

2 problems, I dont have 2007 on my work computer AND in any case IT admin have our Outlook screwed down so that we cannot use Word as an editor.

This makes it hard.

I also am not sure why this line
Code:
Set objInsp = objOutlookMsg.GetInspector
is failing.

It fails for me too.

what I suggest is put it up directly after you set objOutlookMsg. ie

Code:
Set objOutlookMsg = objOutlook.CreateItem(olMailItem) 'Create the message.
[COLOR=Red]Set objInsp = objOutlookMsg.GetInspector[/COLOR]
Set objNameSpace = objOutlook.GetNamespace("MAPI")
It works for me here.

As I cannot use Word this is where I cannot test right now anymore.
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
Thanks for your efforts.

The error you are getting I think is because you need to add Outlook 12.0 to the references.

If you havent got Outlook 2007 it's impossible to replicate.

Thanks anyway
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
Thanks for your efforts.

The error you are getting I think is because you need to add Outlook 12.0 to the references.

If you havent got Outlook 2007 it's impossible to replicate.

Thanks anyway
No that is not the problem. I am not even using your database I have taken the code and am using it alone.

From what I can see there is nothing in this code which is specific to 2007.
 

dfenton

AWF VIP
Local time
Yesterday, 19:04
Joined
May 22, 2007
Messages
469
Code:
On Error Resume Next
bln_QuitOutlook = False
Set olApp = GetObject(, "Outlook.Application")

If Err.Number = 429 Then
    Set olApp = New Outlook.Application
    bln_QuitOutlook = True
Err.Clear
End If

Oy. This kind of code bothers me. It's never a good idea to turn off error handling (i.e., On Error Resume Next) without also setting it back on in the same scope (On Error GoTo 0). Sure, it should cease to be in force when it goes out of scope, but it doesn't reliably do so.

In fact, I prefer to handle the error in an error handler, thus:

Code:
On Error Resume Next
On Error GoTo errHandler

  Set olApp = GetObject(, "Outlook.Application")

exitRoutine:
  bln_QuitOutlook = Not olApp Is Nothing
  Exit Sub ' or Function

errHandler:
  Select Case Err.Number
    Case 429
      Set olApp = New Outlook.Application
    Case Else
      MsgBox Err.Number & ": " & Err.Description, vbExclamation, "Error initializing Outlook!"
  End Select
  Resume exitRoutine
End If
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
Oy. This kind of code bothers me. It's never a good idea to turn off error handling (i.e., On Error Resume Next) without also setting it back on in the same scope (On Error GoTo 0). Sure, it should cease to be in force when it goes out of scope, but it doesn't reliably do so.
Hi David
If I had written that the chicken came before the egg would that also bother you too :).

I dont suppose you know why Inspector could not be set in the pre existing code. I would be interested to know why especially when the code came from someone that appeared to know what they were doing.
 

ghudson

Registered User.
Local time
Yesterday, 19:04
Joined
Jun 8, 2002
Messages
6,195
The below code is what I use to send emails without Outlook 2007 nagging the user with the allow email prompt. Office 2003 users will still get the allow email prompt. Outlook library versions and setting references do not matter with this code. This code does not create another Outlook 2007 session if Outlook is already running.

Code:
Sub SendEmail()
On Error GoTo Err_SendEmail

    Dim sTo As String
    Dim sCC As String
    Dim sSubject As String
    Dim sBody As String
    Dim sAttachmentList As String
    Dim sReplyRecipient As String
    
    Dim sPathFile As String
    sPathFile = "\\Server\Partition\Testing.xls"
    
    'You must key a semicolon between each email name.
    sTo = "johndoe@widgets.com; marysmith@widgets.com"
    sCC = "me@widgets.com"
    sReplyRecipient = "joecleck@widgets.com"
    sSubject = "Important Email"
    sBody = sBody & "Please read then destroy this important email!"
    sAttachmentList = sPathFile
    
    'send email with a file attachment
    'Call SetupOutlookEmail(sTo, sCC, sReplyRecipient, sSubject, sBody, sAttachmentList)
    
    'send email without a file attachment
    Call SetupOutlookEmail(sTo, sCC, sReplyRecipient, sSubject, sBody)

Exit_SendEmail:
    Exit Sub

Err_SendEmail:
    If Err.Number = -2147024894 Then 'Cannot find this file.  Verify the path and file name are correct.
        MsgBox "Email message was not sent.  Please verify the file exists @ " & sPathFile & " before attempting to resend the email.", vbCritical, "Invalid File Attachment"
        Exit Sub
    ElseIf Err.Number = -2147467259 Then 'Outlook does not recognize one or more names.
        MsgBox "Email message was not sent.  Please verify all user names and email addresses are valid before attempting to resend the email.", vbCritical, "Invalid Email Name"
        Exit Sub
    Else
        MsgBox Err.Number & " - " & Err.Description, vbCritical, "SendEmail()"
        Resume Exit_SendEmail
    End If
    
End Sub

Public Function SetupOutlookEmail(ByVal sTo As String, ByVal sCC As String, ByVal sReplyRecipient As String, ByVal sSubject As String, ByVal sBody As String, ParamArray sAttachmentList() As Variant) As Boolean
On Error GoTo Err_SetupOutlookEmail
    
    Dim objOLApp As Object
    Dim outItem As Object
    Dim outFolder As Object
    Dim DestFolder As Object
    Dim outNameSpace As Object
    Dim lngAttachment As Long

    Set objOLApp = CreateObject("Outlook.Application")
    Set outNameSpace = objOLApp.GetNamespace("MAPI")
    Set outFolder = outNameSpace.GetDefaultFolder(6)
    Set outItem = objOLApp.CreateItem(0)

    outItem.To = sTo
    outItem.CC = sCC
    outItem.Subject = sSubject
    outItem.HTMLBody = sBody
    outItem.ReplyRecipients.Add sReplyRecipient
    outItem.ReadReceiptRequested = False

    With outItem.Attachments
        For lngAttachment = LBound(sAttachmentList) To UBound(sAttachmentList)
            .Add sAttachmentList(lngAttachment)
        Next lngAttachment
    End With

    outItem.Send
    'outItem.Display 'setup and open email in edit mode instead of sending the email
    SetupOutlookEmail = True

Exit_SetupOutlookEmail:
    On Error Resume Next
    Set outItem = Nothing
    Set outFolder = Nothing
    Set outNameSpace = Nothing
    Set objOLApp = Nothing
    Exit Function

Err_SetupOutlookEmail:
    If Err.Number = 287 Then 'User stopped Outlook from sending email.
        MsgBox "User aborted email.", vbInformation, "Email Cancelled"
        Resume Exit_SetupOutlookEmail
    Else
        MsgBox Err.Number & " - " & Err.Description, vbCritical, "SetupOutlookEmail()"
        Resume Exit_SetupOutlookEmail
    End If

End Function
 

dfenton

AWF VIP
Local time
Yesterday, 19:04
Joined
May 22, 2007
Messages
469
I never automate Access directly, only using Outlook Redemption, as this avoids all the security prompts. So, no, I don't know why the inspector could not be set. I don't even know what it is!
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
Thanks to ghudson. That piece of code works fine using an existing Outlook session if there is one, alternatively creating a new session. I'm trying to work out how to add a Signature now. Any help would be appreciated !!
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
I have managed to add a signature with some code I found on the forum. However, my signature is an HTM file which contains some images(logos). When Outlook is already running it displays the images(logos) fine, when Outlook is NOT running I get a red cross and an error message 'The image part with relationship ID rID1 was not found in the file'
 

darbid

Registered User.
Local time
Today, 01:04
Joined
Jun 26, 2008
Messages
1,428
I have managed to add a signature with some code I found on the forum. However, my signature is an HTM file which contains some images(logos). When Outlook is already running it displays the images(logos) fine, when Outlook is NOT running I get a red cross and an error message 'The image part with relationship ID rID1 was not found in the file'
I have no idea, but if you show your code and I can reproduce a test I will have a look for you.
 

wllsth

Registered User.
Local time
Today, 00:04
Joined
Sep 17, 2008
Messages
81
I've resolved the issue by placing my image(logo) on the web and referencing to that rather than to my local machine. Here's the amended version of your code. Thanks for all your help.
Code:
Private Sub Command223_Click()
RunCommand acCmdSaveRecord
DoCmd.OpenReport "QuotationPrint", acViewReport, , "[EstimateID]=" & [ID]
DoCmd.OutputTo acOutputReport, "QuotationPrint", acFormatPDF, "C:\Documents and Settings\Quotation.pdf"
On Error GoTo Err_SendEmail
    Dim sTo As String
    Dim sCC As String
    Dim sSubject As String
    Dim sBody As String
    Dim sAttachmentList As String
    Dim sReplyRecipient As String
        Dim sPathFile As String
    sPathFile = "C:\Documents and Settings\Quotation.pdf"
 
    'You must key a semicolon between each email name.
    sTo = [Contact e-Mail]
    sCC = ""
    sReplyRecipient = " "
    sSubject = [Site Address] & " - Quotation"
 
    sAttachmentList = sPathFile
 
    ' sBody = " "
 
    'send email with a file attachment
    Call SetupOutlookEmail(sTo, sCC, sReplyRecipient, sSubject, sBody, sAttachmentList)
 
    'send email without a file attachment
    'Call SetupOutlookEmail(sTo, sCC, sReplyRecipient, sSubject, sBody)
Exit_SendEmail:
    Exit Sub
Err_SendEmail:
    If Err.Number = -2147024894 Then 'Cannot find this file.  Verify the path and file name are correct.
        MsgBox "Email message was not sent.  Please verify the file exists @ " & sPathFile & " before attempting to resend the email.", vbCritical, "Invalid File Attachment"
        Exit Sub
    ElseIf Err.Number = -2147467259 Then 'Outlook does not recognize one or more names.
        MsgBox "Email message was not sent.  Please verify all user names and email addresses are valid before attempting to resend the email.", vbCritical, "Invalid Email Name"
        Exit Sub
    Else
        MsgBox Err.Number & " - " & Err.Description, vbCritical, "SendEmail()"
        Resume Exit_SendEmail
    End If
 
End Sub
Public Function SetupOutlookEmail(ByVal sTo As String, ByVal sCC As String, ByVal sReplyRecipient As String, ByVal sSubject As String, ByVal sBody As String, ParamArray sAttachmentList() As Variant) As Boolean
On Error GoTo Err_SetupOutlookEmail
 
    Dim objOLApp As Object
    Dim outItem As Object
    Dim outFolder As Object
    Dim DestFolder As Object
    Dim outNameSpace As Object
    Dim lngAttachment As Long
    Dim SigString As String
    Dim Signature As String
 
    Set objOLApp = CreateObject("Outlook.Application")
    Set outNameSpace = objOLApp.GetNamespace("MAPI")
    Set outFolder = outNameSpace.GetDefaultFolder(6)
    Set outItem = objOLApp.CreateItem(0)
    sBody = "<H3><B></B></H3>" & _
              "Thank you for your recent enquiry.<br><br>" & _
              "Please find attached our quotation, if you have any queries then please do not hesitate to contact us.<br>" & _
              "<br><br><B>Thanking you in anticipation</B>"
    SigString = "C:\Documents and Settings\Tom\My Documents\TomWSig.htm"
    If Dir(SigString) <> "" Then
        Signature = GetBoiler(SigString)
    Else
        Signature = ""
    End If
 
    outItem.To = sTo
    outItem.CC = sCC
    outItem.Subject = sSubject
    outItem.HTMLBody = sBody & "<br><br>" & Signature
    outItem.ReplyRecipients.Add sReplyRecipient
    outItem.ReadReceiptRequested = False
    With outItem.Attachments
        For lngAttachment = LBound(sAttachmentList) To UBound(sAttachmentList)
            .Add sAttachmentList(lngAttachment)
        Next lngAttachment
    End With
    'outItem.Send
    outItem.Display 'setup and open email in edit mode instead of sending the email
    SetupOutlookEmail = True
Exit_SetupOutlookEmail:
    On Error Resume Next
    Set outItem = Nothing
    Set outFolder = Nothing
    Set outNameSpace = Nothing
    Set objOLApp = Nothing
    Exit Function
Err_SetupOutlookEmail:
    If Err.Number = 287 Then 'User stopped Outlook from sending email.
        MsgBox "User aborted email.", vbInformation, "Email Cancelled"
        Resume Exit_SetupOutlookEmail
    Else
        MsgBox Err.Number & " - " & Err.Description, vbCritical, "SetupOutlookEmail()"
        Resume Exit_SetupOutlookEmail
    End If
End Function
Function GetBoiler(ByVal sFile As String) As String
'Dick Kusleika
    Dim fso As Object
    Dim ts As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
    GetBoiler = ts.readall
    ts.Close
End Function
 

constantG

Registered User.
Local time
Today, 00:04
Joined
Jun 24, 2009
Messages
92
Ghudson:

I am using your code for automation however I have a problem. How do you introduce a "from" field, this is needed as the system I will be running my utility on uses microsoft exchange server.
It seems that "outItem" does not recognise a "from" attribute.

Thanks.
 

ghudson

Registered User.
Local time
Yesterday, 19:04
Joined
Jun 8, 2002
Messages
6,195
I do not believe that Outlook will allow you to automate a FROM since Outlook tries to prevent spoofing. If I am wrong, I would love to see the code on how to do it. ;-)
 

Users who are viewing this thread

Top Bottom