VBA code to send email

VBA code to send email

mohandis2
Advocate Advocate
866 Views
2 Replies
Message 1 of 3

VBA code to send email

mohandis2
Advocate
Advocate

I could make a routin that prints my drawing in pdf, I want to send these pdf files via an email using outlook, can anyone help?

Regards.

 

0 Likes
867 Views
2 Replies
Replies (2)
Message 2 of 3

norman.yuan
Mentor
Mentor

To send email from your AutoCAD VBA code via Outlook, you need to automate Outlook through its COM API. Needless to say, Outlook has to be installed and ready for the current log-in user to send email. The code to make Outlook send an email is fairly simple:

 

Public Sub SendEmail()

    Dim outobj As Object
    Dim mailobj As Object
    Dim strMsg As String
    
    On Error Resume Next
    
    Set outobj = GetObject(, "Outlook.Application")
    If outobj Is Nothing Then
        Set outobj = CreateObject("Outlook.Application")
    End If
    On Error GoTo 0
    
    If outobj Is Nothing Then
        MsgBox "Cannot obtain Outlook application object!"
        Exit Sub
    End If
    
    Set mailobj = outobj.CreateItem(0)
    strMsg = "This is test email"

    With mailobj
     .To = "norman.yuan.fsj@gmail.com"
     .Subject = strMsg
     .Send
    End With
    
    'Clear the memory
    Set outobj = Nothing
    Set mailobj = Nothing

End Sub

 The code uses late binding (that is, no need to set reference to Outlook library). You need to add a bit more code to add attachment to the email, though. You can open Outlook VBA editor and use Object Browser to find out how to add attachment to an email.

 

Depending on Outlook version and its security settings, a security warning window may pops up, saying something like " an application is trying to use Outlook...." and user may have to click OK to allow the code to continue.

Norman Yuan

Drive CAD With Code

EESignature

0 Likes
Message 3 of 3

mohandis2
Advocate
Advocate

Thanks for the reply, it worked fine.

My other problem is how to detect selected sheets only.

 

0 Likes