Click here to Skip to main content
Click here to Skip to main content

How to Deliver an Email with an Attachment of the Active Working Document from Microsoft Office Word

, 4 Sep 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
We discuss Microsoft Office Word 7 addIn, which is able to deliver an email with little text and able to attach the current document as a Zip/Compress file or standard Microsoft Office Word document file format & send the email from Microsoft Office Word Interface.

Table of Contents

  1. Introduction
  2. A small story behind the topics
  3. What are we going to discuss
  4. Create your first Microsoft Office AddIn Project
    1. Add menu item into Microsoft Office Application context menu
    2. Insert simple text into your current active document
    3. Call a win32Form from your AddIn
  5. Store active document into My Document Folder
    1. Zip active document into My Document Folder
  6. Access Microsoft Office Outlook MAPI from Microsoft Office Word
    1. Retrieve and display contact list from Microsoft Outlook Contact Folder
    2. Write an email and auto attach the document
    3. Delivery your email with attachment to Microsoft Office Outlook
  7. Points of Interest
  8. Reference
  9. Conclusion
  10. History

1. Introduction

I would like to share a little scenario first. Yes you may skip this section, but I would request you to read although the scenarios do not directly belong to the actual article or it will not give you some technical knowledge, but I think it’s a little bit important to know because this will give you the actual idea / purpose of this article. Let’s start with a small story.

2. A Small Story Behind the Topics

“TadpoleTechnologies Ltd.” which is a computer software development company, the main character of this scenario is an office executive. She has a number of job responsibilities and one of her major tasks is to write various types of business proposals, issues, prepare reporting, etc., and send it to the concerned person. She uses Microsoft Office Word 7 for writing, editing, reporting, etc., and Microsoft Office Outlook 7 for sending each item.

Her working procedure is something like, at first she opens Microsoft Office Word 7 and starts writing, when the writing task is done, she stores it in a particular location, after that she closes the Microsoft Office Word 7 application and zips/compresses the file. Finally, she opens Microsoft Office Outlook, attaches the file and writes some text and sends this email. It’s very simple, but she has to do this task more than one hundred times every day. She was so upset, to complete a single task she needs approximately five minutes. One day she come to my desk and requests me to assign her some other jobs, she can’t do this anymore. Well, I requested her to give me one day to resolve this issue.

3. What Are We Going to Discuss

Finally, I gave her a very funny solution and I was wondering whether she was happy with that. Actually, I developed a Microsoft Office Word 7 addIn, which is able to deliver an email with a little text and is able to attach the current document as a Zip/Compress file or standard Microsoft Office Word document file format & send the email from Microsoft Office Word Interface.

Ooh, not such a long story, I don’t want some more on that; Anyway guys, I hope you got the idea on what we are actually trying to discuss. Yes, you are right, in this article, we will discuss how we can deliver a Microsoft Office Word document in a normal format or zip format to Microsoft Office Outlook directly for sending this to someone requesting from Office Word Interface while working on the same document.

4. Create Your First Microsoft Office AddIn Project

To develop an addIn for Microsoft Office System, i.e., Outlook 2007, Word 2007 etc., You need to learn a few basic things, for example how to use Microsoft Visual Studio 2008/2010 templates for office development and some other stuff as well. I would request you to read my previous article which is about to creating AddIn by using Microsoft Visual Studio from the location below:

I hope now you have a very good understanding on this area. Let’s go ahead.

4.1 Add Menu Item into Microsoft Office Application Context Menu

Well, I already discussed how to create / add a menu item into the Microsoft Office Application context menu in my previous article, anyway; if you want to read, please go to the link below:

4.2 Insert Simple Text into Your Current Active Document

Great! Now we will take a little look at how we can add some text content into your active document from the C# code. It's quite simple, we just need to know how we can use the "Selection.InsertAfter()" method. A sample code snippet is given below:

Code snippet example - 1

Word.Application applicationObject = 
	Globals.ZipSenderAddIn.Application as Word.Application;
Globals.ZipSenderAddIn.Application.Selection.InsertAfter
		("I love CodeProject" + Environment.NewLine);
Globals.ZipSenderAddIn.Application.Selection.InsertAfter
		("Author : " + "Md. Marufuzzaman" + Environment.NewLine);
Globals.ZipSenderAddIn.Application.Selection.InsertAfter
		("Thanks To : " + Environment.UserName + Environment.NewLine);

More information on Selection.InsertAfter() could be found at this link.

4.3 Call a win32Form from your AddIn

To call a WinForm from C#.NET Microsoft Office AddIn is nothing new, it's just like we call a WinForm in any Desktop application development. In this AddIn, I used win32Form named "ZipSender.cs". A sample code snippet is given below:

Code snippet example - 2

ZipSenderWord7AddIn.Win32Forms.ZipSender zipSender = new Win32Forms.ZipSender();
zipSender.Show(); 

5. Store Active Document into My Document Folder

Okay; in this section we will discuss how we can save / store the active document; This is really very simple , Microsoft.Office.Interop.Word namespace provide a number of methods, properties and delegate as well to make our development process much more faster.Well, what we actually do, we just create a function SaveDocument() which will take a parameter i.e., the document fullpath with the name. Finally we create an instance on the Microsoft Office Application and after that we call the SaveAs() method with few required parameter for example, document name, path, type, etc. A sample code snippets is given below:

Code snippet example - 3

public bool SaveDocument(string fileName)
{
    string filePath = this.GetMyDocuments();
    bool retValue = false;
    fullPath = filePath + "\\" + fileName;
    
    Word.Application applicationObject = 
		Globals.ZipSenderAddIn.Application as Word.Application;
    try
    {
        applicationObject.ActiveDocument.SaveAs(filePath + "\\" + fileName
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing
                                                , Type.Missing);
        retValue = true;                
    }
    catch (Exception exception)
    {
        retValue = false;
        MessageBox.Show("Error: " + exception.Message);
    }
    
    return retValue;
}

More information about ActiveDocument.SaveAs() could be found at this link.

5.1 Zip Active Document into My Document Folder

I wrote a very simple function for zipping the document, I use an open source tool for zipping the document. A sample code snippet is given below:

Code snippet example - 4

public bool ZipDocument(string accessPath, string fileExt)
{
    bool retValue = false;
    
    ZipFile zipFiles = new ZipFile();
    fileName = Path.GetFileName(accessPath);
    
    if (fileExt != ".docx")
    {
        try
        {
            zipFiles.AddFile(accessPath + ".docx", "Document");
            zipFiles.Save(fileName + ".zip");
            retValue = true;
        }
        catch (Exception exception)
        {
            retValue = false;
            MessageBox.Show("Error: " + exception.Message);
        }
    }
    else
    {
        retValue = true;
    }
    return retValue;
}

More information about the Zip API could be found at this link.

6. Access Microsoft Outlook MAPI from Microsoft Office Word

To access Microsoft Office Outlook from Microsoft Office Word, we will use Microsoft.Office.Interop.Outlook namespace provided by Microsoft. Well, I wrote the following function to get the contacts from Microsoft Office Outlook contact folder:

6.1 Retrieve and Display Contact List from Microsoft Outlook Contact Folder

Code snippet example - 5

public List<string> GetContact()
{
    List<string> contactList = new List<string>();
    
    try
    {
        outlookObj = new Outlook.Application();
        olNameSpace = outlookObj.GetNamespace("MAPI");
        olNameSpace.Logon(null, null, true, true);
        Outlook.MAPIFolder contactsFolder =  
        (Outlook.MAPIFolder)outlookObj.Session.GetDefaultFolder
        	(Outlook.OlDefaultFolders.olFolderContacts);
        foreach (Outlook.ContactItem contactItem in contactsFolder.Items)
        {
            if (contactItem.Email1Address !=null)
            {
                contactList.Add(contactItem.Email1Address);
            }                  
        }           
    }
    catch 
    {
         
    }
    
    return contactList;
}

The following figure A shows the contact list.

operation-1.png

More information about the Microsoft.Office.Interop.Outlook could be found at this link.

6.2 Write an Email and Auto Attach the Document

I create a very simple interface to add the email address, subject, email body text, etc. Well, the following figure B shows the basic interface to send an email.

Figure - B

operation-2.png

If you look closely, then you will find a checkbox which will give you the functionalities that the attached file will be a normal Microsoft Office Word default format or it will be attached as a zip file. I wrote a few functions which will attach the file, add all the email content and deliver to Microsoft Outlook Outbox folder. A sample code snippet is given below.

6.3 Delivery your Email with Attachment to Microsoft Office Outlook

Code snippet example - 6

private void buttonSend_Click(object sender, EventArgs e)
{
    this.labelDeliveryStatus.Text = "Sending...";
    this.progressBarZipSender.Value = 25;
    ZipSenderTools zipSenderTools = new ZipSenderTools();
    name = this.textBoxFileName.Text;
    this.buttonSend.Enabled = false; 
    try
    {
        if (name != null)
        {
            if (zipSenderTools.SaveDocument(name))
            {
                if (zipSenderTools.ZipDocument(zipSenderTools.fullPath, fileExtType))
                {
                    this.progressBarZipSender.Value = 50;
                    if (zipSenderTools.SubmitToOutlook(this.textBoxSendTo.Text 
                                                     , this.textBoxCcTo.Text
                                                     , this.textBoxSubject.Text
                                                     , this.richTextBoxBody.Text
                                                     , zipSenderTools.fullPath + 
								fileExtType))
                    {
                        this.progressBarZipSender.Value = 100;
                        this.labelDeliveryStatus.Text = "Email successfully sent.";
                        MessageBox.Show("Delivery Success.","Status", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                        zipSenderTools.DeleteZipDocument
                        (zipSenderTools.fullPath + fileExtType, fileExtType);
                        this.Close();
                    }
                    else
                    {
                        this.progressBarZipSender.Value = 0;
                        this.labelDeliveryStatus.Text = "Email sending fail.";
                        MessageBox.Show("Delivery Fail","Status", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        zipSenderTools.DeleteZipDocument
                        (zipSenderTools.fullPath + fileExtType, fileExtType);
                    }
                }
            }
        }
        else
        {
            MessageBox.Show("Enter a valid file name.");
        }
    }
    catch (Exception exception)
    {
        MessageBox.Show("Error: " + exception.Message);
    }
    this.buttonSend.Enabled = true; 
}

Now, what? We are almost done! After successful delivery, it will display a message. The following figure C shows a successful delivery and figure D shows the Outlook status:

Figure - C

delivery-success.png

Figure - D

outlook-delivery.png

7. Points of Interest

I implemented this only for Microsoft Office Outlook. I have a plan to add Gmail, Yahoo, AOL in my next version.

8. Reference

9. Conclusion

It's all about fun, hope this might be helpful to someone.

10. History

  • 2nd September, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Md. Marufuzzaman
Architect
Bangladesh Bangladesh
A highly experienced leader with successful track record of software development, product innovations, brand management and corporate communication etc. Some successful product innovations have also achieved and awards “Most Valuable Professional” (MVP) at 2010 and 2011 by codeproject.com and also selected as a mentor of codeproject.com. Published over 100 technical articles in various software development resource sites (i.e., codeprojetc.com, Microsoft MSDN, and IEEE & IBM (In progress)) and various IT Forums, Blogs etc.
 
Over ten years of professional experiences in ICT field having extensive experience in formulating corporate vision and long term strategy. Leading development related functions including design, development, services, data management and analytics, customer experience management, content services, digital analytics and optimization.
 
An individual with results-driven approach and relentless in pursuit of excellence from a business and organizational standpoint. Believes in transparency, commitment and teamwork.
 
Expertise: Software/Solution Architect, SaaS platform base application, Large scale win32/web based business software solutions, enterprise applications, integration, etc.
 
Technologies/Tools: Microsoft.Net version 05/08/10/12, Microsoft SQL Server version 7/2K/05/08/12 , Oracle version 10/11, MySql version 5.1, 5.5, PS2, Visual C#, R, VB.NET, ASP.NET, PHP, API, MVC, WebAPI , Add-In Visual Basic etc.,. I have also more than two years’ of strong experience in mobile-VAS (platform development).
 
Points of Interest: Technology and research & development especially focused on business functionalities and social business areas as well, few stuff including:
 
1.R&D on new techniques as required to increase business revenue.
2.Urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc., using innovative technical solutions.
3.Research and innovative product development.
4.Etc.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun30-Apr-14 20:32 
QuestionWhy not just 'File -> Send to' ??? PinmemberDavid O'Neil5-Sep-11 7:12 
AnswerRe: Why not just 'File -> Send to' ??? PinmvpMd. Marufuzzaman5-Sep-11 7:59 
QuestionRecommend change of title? PinmemberPete BSC3-Sep-11 9:00 
AnswerRe: Recommend change of title? PinmvpMd. Marufuzzaman3-Sep-11 14:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 4 Sep 2011
Article Copyright 2011 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid