Siddhant Singh
Siddhant Singh

Reputation: 1

How to create a mailitem?

I'm trying to send the active Excel workbook as an attachment via Outlook.

Whenever I run the code it says

Invalid use of New key word

at New Outlook.MailItem`.

Sub SendOutlook()
    'Declaring Variables
    Dim OutlookApp  As Outlook.Application
    Dim OutlookEmail  As Outlook.MailItem

    'Assigning variables to create outlook application and mailitem
    Set OutlookApp = New Outlook.Application
    Set OutlookEmail = New Outlook.MailItem
    
    With OutlookEmail
        'Format of the mail
        .BodyFormat = olFormatPlain
        'Body of the mail
        .Body = "Dear Someone" & vbNewLine & "How are you?"
        'To whom you want to send mail
        .To = "[email protected]"
        'Subject of mail
        .Subject = "Write Subject Here"
        'TO add an attachment
        .Attachments.Add ActiveWorkbook.FullName
        'sends the mail
        .Send
    End With
    
End Sub

Upvotes: 0

Views: 2374

Answers (3)

Skynet
Skynet

Reputation: 84

You can use a programmatic approach with the following:

Option Explicit

Private outlook_app As Object
Private outlook_mailItem As Variant

Sub send_email()

    Set outlook_app = CreateObject("Outlook.Application")
    With outlook_app.CreateItem(outlook_mailItem)
        .To = "[email protected]"
        .Subject = "Write Subject Here"
        .Body = "Dear Someone" & vbNewLine & "How are you?"
        .send
    End With
    Set outlook_app = Nothing

End Sub

Upvotes: 0

FunThomas
FunThomas

Reputation: 29181

You cannot create a MailItem via New. It must be created using CreateItem of the the Outlook Application Object.

   Set OutlookApp = New Outlook.Application
   Set OutlookEmail = OutlookApp.CreateItem(olMailItem)

Upvotes: 1

Siddhant Singh
Siddhant Singh

Reputation: 1

As far as I got to know from the research is that Programmatic access to sending emails is a security risk, so it's not allowed via VBA.

Upvotes: -2

Related Questions