VBA for Outlook - Automate all your email tasks

VBA for Outlook


Open message file

Sub OpenMsgFile()

    Dim olApp As Object
    
Dim olMsg As Object   

    'Create Outlook Application object
    Set olApp = CreateObject("Outlook.Application")    

    'Open .msg file
    Set olMsg = olApp.CreateItemFromTemplate("C:\Users\username\Downloads\test.msg")    

    'Display the message
    olMsg.Display    

    'Clean up
    Set olMsg = Nothing
    
Set olApp = Nothing    

End Sub

Code explanation:
यह VBA macro Outlook की .MSG e-mail file को automatic खोलने और दिखाने के लिए उपयोग किया जाता है। Sub OpenMsgFile() का मुख्य उद्देश्य Excel या किसी भी VBA-enabled application से सीधे Outlook e-mail file को access करना है। यह code खास तौर पर Email Automation, Outlook VBA, Finance Reporting और Audit Process में बहुत उपयोगी है।

इस code में सबसे पहले CreateObject("Outlook.Application") के जरिए Microsoft Outlook का एक नया Application object बनाया जाता है। इससे VBA को Outlook के साथ interact करने की अनुमति मिलती है। इसके बाद CreateItemFromTemplate method का उपयोग करके local system में save की गई .msg file को खोला जाता है। .msg file आमतौर पर Outlook e-mail का save किया हुआ format होती है, जिसमें Subject, Body, Attachments और Sender की जानकारी शामिल होती है।

दिए गए path "C:\Users\username\Downloads\test.msg" को अपनी जरूरत के अनुसार बदला जा सकता है। जैसे ही यह file load होती है, olMsg.Display command के जरिए e-mail को Outlook window में open कर दिया जाता है। इससे user e-mail को बिल्कुल उसी तरह देख सकता है जैसे वह Outlook inbox में दिखाई देता है।

यह macro खासकर तब उपयोगी होता है जब किसी process में Pre-Saved Emails, System Generated Messages या Client Communication Records को बार-बार खोलने की जरूरत होती है। उदाहरण के लिए, Finance या Compliance team पुराने e-mail reference को जल्दी access कर सकती है। इससे manually Outlook खोलकर file ढूंढने का समय बचता है।

Code के अंत में Set olMsg = Nothing और Set olApp = Nothing लिखा गया है, जो memory को clean करता है और system पर अनावश्यक load नहीं पड़ने देता। यह एक अच्छी VBA practice मानी जाती है और बड़े automation projects में बहुत जरूरी होती है।


Save Email Attachments

Sub SaveEmailAttachments()
    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.Namespace
    Dim olFolder As Outlook.MAPIFolder
    Dim olItem As Object
    Dim olAttachment As Outlook.Attachment
    Dim savePath As String
    Dim fileName As String
    Dim i As Long
    
    ' Set folder path where you want to save attachments
    savePath = "C:\Users\username\Downloads\test\"
    
    ' Ensure path ends with backslash
    If Right(savePath, 1) <> "\" Then savePath = savePath & "\"
    
    'Create Outlook objects
    Set olApp = Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")
    
    ' Select folder (e.g., Inbox)
    Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox)
    
    'Loop through each mail item in the folder
    For Each olItem In olFolder.Items
        'Check if it's a mail item
        If TypeName(olItem) = "MailItem" Then
            'Check if it has attachments
            If olItem.Attachments.Count > 0 Then
                For i = 1 To olItem.Attachments.Count
                    Set olAttachment = olItem.Attachments(i)
                    fileName = olAttachment.fileName
                    
                    ' Save attachment
                    olAttachment.SaveAsFile savePath & fileName
                Next i
            End If
        End If
    Next
olItem
    
    MsgBox "Attachments saved to: " & savePath, vbInformation
End Sub

Code explanation:
यह VBA macro Microsoft Outlook e-mail से attachment को automatic save करने के लिए बनाया गया है। Sub SaveEmailAttachments() का मुख्य उद्देश्य Outlook Inbox में आने वाले e-mails से सभी attachments को एक तय local folder में save करना है। यह code खास तौर पर Email Automation, Outlook VBA, Document Management और Office Productivity के लिए बहुत उपयोगी है।

Code की शुरुआत में Outlook से जुड़े सभी ज़रूरी objects declare किए गए हैं, जैसे Outlook.Application, Namespace, MAPIFolder और Attachment। इसके बाद savePath variable में वह folder path दिया गया है, जहाँ attachment save होंगे। Code यह भी check करता है कि folder path के अंत में backslash ( \ ) मौजूद है या नहीं, जिससे file save करते समय कोई error न आए।

Set olApp = Outlook.Application और GetNamespace("MAPI") के जरिए VBA को Outlook से connect किया जाता है। इसके बाद GetDefaultFolder(olFolderInbox) का उपयोग करके सीधे Inbox folder को access किया जाता है। यह तरीका Outlook VBA Automation में सबसे ज़्यादा इस्तेमाल किया जाता है।

इसके बाद For Each olItem In olFolder.Items loop के जरिए Inbox के हर item को एक-एक करके पढ़ा जाता है। TypeName(olItem) = "MailItem" condition यह सुनिश्चित करती है कि केवल e-mail item पर ही काम हो, न कि meeting request या notes पर। अगर किसी e-mail में attachment मौजूद होते हैं, तो Attachments.Count के ज़रिए उनकी संख्या check की जाती है।

हर attachment को SaveAsFile method से तय folder में save किया जाता है। File का नाम वही रखा जाता है जो e-mail में दिया गया होता है। यह प्रक्रिया पूरी तरह automatic होती है और इसमें किसी manual download की ज़रूरत नहीं पड़ती।

यह macro खास तौर पर Finance, HR, Audit, Compliance और Reporting Teams के लिए बहुत उपयोगी है, जहाँ रोज़ बड़ी संख्या में e-mail attachment आते हैं। इससे समय की बचत होती है और file management आसान हो जाता है।


Send Mail Notification

Sub SendMailNotification()
' ********* Send Mail Notification based on recepient in list in scheduling sheet ************
    Dim oMSOutlook As Object
    Dim oEmail As Object
    Dim sName As String
    sName = "Summary" 'change sheet name here

    ReporterName = Environ$("UserName")
    If ReporterName = "" Then
        ReporterName = Mid(WorksheetFunction.Substitute((Environ$("UserProfile")), "\", "_", 2), WorksheetFunction.Find("_", WorksheetFunction.Substitute((Environ$("UserProfile")), "\", "_", 2)) + 1, 8)
    End If
    SignatureReporterName = "XYZ" 'Application.UserName
    DestinationDriveFolderLink = Sheets(sName).Range("F32").Value
    UserComments = "<a href=""" & Sheets(sName).Range("F40").Value & """>Final Report</a>"
    FAQ = "<b>Note:</b> Please feel free to share your feedback or report issues by replying to this email. For common issues, refer to the " & "<a href=""" & Sheets(sName).Range("F48").Value & """>FAQ</a>."
    FirstLine = "Dear All," 'Sheets(sName).Range("F72").Value
    SecondLine = "The Final Report is now updated with " & "<b>Day +3</b>" & " financials. " & "<b>All tabs in the report are updated</b>" & ". Please use the link below to view the dashboard."
    
    If Left(DestinationDriveFolderLink, 2) = "\\" Then
        If Sheets(sName).Range("F44") = "" Then
            DestinationDriveFolderLink = Sheets(sName).Range("F32").Value & "\" & ActiveWorkbook.Name
        Else
            DestinationDriveFolderLink = Sheets(sName).Range("F32").Value & "\" & Sheets(sName).Range("F44") & Right(ActiveWorkbook.Name, 5)
        End If
    ElseIf Left(DestinationDriveFolderLink, 4) = "http" Then
        DestinationDriveFolderLink = WorksheetFunction.Substitute(DestinationDriveFolderLink, "\", "/")
    Else
        If Sheets(sName).Range("F44") = "" Then
            DestinationDriveFolderLink = Sheets(sName).Range("F32").Value & "\" & ActiveWorkbook.Name
        Else
            DestinationDriveFolderLink = Sheets(sName).Range("F32").Value & "\" & Sheets(sName).Range("F44") & Right(ActiveWorkbook.Name, 5)
        End If
    End If
    Link1 = "<A HREF=""" & DestinationDriveFolderLink & """>" & DestinationDriveFolderLink & "</A>"
    If Sheets(sName).Range("F36").Value = "" Then
        ToSenderName = ReporterName
    Else
        ToSenderName = Sheets(sName).Range("F36").Value '& ";" & ReporterName
    End If
    Set oMSOutlook = CreateObject("Outlook.Application")
    Set oEmail = oMSOutlook.CreateItem(olMailItem)
    sSubject = "Final Report" 'WorksheetFunction.Substitute(ActiveWorkbook.Name, ".xlsm", "")
    MsgBody = "<font size=""2"" face=""Arial"" color=""Black"">" & _
            FirstLine & "<br>" & "<br>" & _
            SecondLine & "<br>" & "<br>" & _
            UserComments & "<br>" & "<br>" & "<br>" & _
            FAQ & "<br>" & "<br>" & _
            "Best Regards," & "<br>" & _
            SignatureReporterName
    On Error GoTo DefaultMail:
    With oEmail
        .SentOnBehalfOfName = "Final.Report@gmail.com"
        .To = "" 'ToSenderName
        .CC = "" 'Sheet1.Range("I37")
        .BCC = ToSenderName
        .Subject = "" & sSubject
        .HTMLBody = MsgBody
        '.Send
        .display
    End With
DefaultMail:
    If Err.Number <> 0 Then
        MsgBody2 = "<font size=""2"" face=""Arial"" color=""Black"">" & _
                   "Message: Report generated successfully and saved in below path: " & "<br>" & "<br>" & _
                   "Path: " & Link1 & "<br>" & "<br>" & _
                   "Error: Mail Notification is not received to Recipients, as Mail-ID/username are not correct OR blank OR not seperated by Semicolon" & "<br>" & "<br>" & _
                   "Best Regards," & "<br>" & _
                   SignatureReporterName
        With oEmail
            .To = ReporterName
            .Subject = "" & sSubject
            .HTMLBody = MsgBody2
            .Send
        End With
    Else
        Flag = False
    End If
    Set oMSOutlook = Nothing
    Set oEmail = Nothing
End Sub

Code explanation:
यह VBA macro Excel से Outlook e-mail notification automatic भेजने के लिए बनाया गया है। Sub SendMailNotification() का मुख्य उद्देश्य यह है कि जैसे ही कोई Final Report या dashboard update हो, उसकी जानकारी तय किए गए recipient को अपने आप e-mail के माध्यम से मिल जाए। यह code खास तौर पर MIS Reporting, Finance Reporting, Management Communication और Automation के लिए बहुत उपयोगी है।

इस macro में recipients, link और message की जानकारी Excel की Summary sheet से ली जाती है। इससे e-mail पूरी तरह dynamic बन जाता है और हर बार code बदलने की जरूरत नहीं पड़ती। Environ$("UserName") के जरिए report बनाने वाले user का नाम लिया जाता है और उसी के आधार पर mail sender या BCC list तैयार होती है।

Code में पहले यह check किया जाता है कि report का location local drive, network drive या SharePoint/HTTP link है। उसी अनुसार link को सही format में बदला जाता है। इसके बाद HTML tags का उपयोग करके एक professional e-mail body बनाई जाती है, जिसमें Final Report लिंक, FAQ लिंक, notes और signatures शामिल होते हैं।

CreateObject("Outlook.Application") के जरिए Outlook से connection बनाया जाता है और CreateItem(olMailItem) से नया e-mail तैयार किया जाता है। .HTMLBody का उपयोग करने से mail में clickable link, bold text और साफ formatting दिखाई देती है। .SentOnBehalfOfName के जरिए mail किसी common mailbox या team mail ID से भेजा जा सकता है, जैसे कि Final.Report@gmail.com।

इस macro में Error Handling भी शामिल है। अगर recipient का e-mail ID गलत हो या खाली हो, तो code automatically एक वैकल्पिक mail report बनाने वाले user को भेज देता है। इससे यह पता चल जाता है कि report तो बन गई है, लेकिन notification सही तरीके से नहीं गया।


Send an Email from Excel/Word/PowerPoint

Must add a reference: Microsoft Outlook Object Library

Sub SendEmail()
    Dim OutApp As Object, Mail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set Mail = OutApp.CreateItem(0)
    With Mail
        .To = "someone@example.com"
        .Subject = "Hello from VBA"
        .Body = "Automated message sent at " & Now
        .Send
    End With
End Sub

Code explanation:
यह VBA code Microsoft Excel से Outlook e-mail automatic भेजने के लिए उपयोग किया जाता है। इस macro को चलाने से पहले VBA Editor में Microsoft Outlook Object Library का reference जोड़ना ज़रूरी होता है, ताकि Excel और Outlook के बीच सही तरीके से connection बन सके। Sub SendEmail() एक सरल लेकिन बहुत उपयोगी automation उदाहरण है, जो manual e-mail भेजने का समय बचाता है।

इस code में सबसे पहले CreateObject("Outlook.Application") के ज़रिए Microsoft Outlook का एक नया application object बनाया जाता है। इसके बाद CreateItem(0) का उपयोग करके एक नया mail item तैयार किया जाता है। यह mail बिल्कुल उसी तरह होता है जैसे आप Outlook में नया e-mail बनाते हैं। इससे VBA को Outlook के सभी mail features का access मिल जाता है।

With Mail block के अंदर e-mail की मुख्य जानकारी set की जाती है। .To property में recipient का e-mail address डाला जाता है। .Subject में e-mail का विषय लिखा जाता है, जिससे recipient को mail का उद्देश्य तुरंत समझ में आ जाए। .Body में mail का message लिखा जाता है। इस उदाहरण में Now function का उपयोग किया गया है, जिससे mail में automatic date और time जुड़ जाता है। यह feature reporting और login के लिए बहुत उपयोगी होता है।

.Send command e-mail को बिना किसी manual intervention के तुरंत भेज देती है। अगर चाहें तो .Send की जगह .Display का उपयोग करके mail को पहले screen पर दिखाया जा सकता है। यह तब उपयोगी होता है जब user भेजने से पहले mail को check करना चाहता है।

यह VBA macro Excel VBA Email Automation, Outlook Automation, Auto Email Notification, और Office Productivity के लिए बेहद फायदेमंद है। इसका उपयोग Finance Reports, MIS Updates, Daily Status Reports, System Alerts और Workflow Notifications जैसे कई real-world scenario में किया जाता है।

एक टिप्पणी भेजें

Please do not enter any spam link in the comment box.

और नया पुराने