Click here to Skip to main content
15,881,687 members
Articles / Productivity Apps and Services / Microsoft Office

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

Rate me:
Please Sign up or sign in to vote.
4.83/5 (10 votes)
4 Sep 2011CPOL7 min read 42.3K   657   17   5
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

C#
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

C#
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

C#
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

C#
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

C#
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

C#
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)



Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun30-Apr-14 19:32
Humayun Kabir Mamun30-Apr-14 19:32 
QuestionWhy not just 'File -> Send to' ??? Pin
David O'Neil5-Sep-11 6:12
professionalDavid O'Neil5-Sep-11 6:12 
AnswerRe: Why not just 'File -> Send to' ??? Pin
Md. Marufuzzaman5-Sep-11 6:59
professionalMd. Marufuzzaman5-Sep-11 6:59 
QuestionRecommend change of title? Pin
Pete BSC3-Sep-11 8:00
Pete BSC3-Sep-11 8:00 
AnswerRe: Recommend change of title? Pin
Md. Marufuzzaman3-Sep-11 13:47
professionalMd. Marufuzzaman3-Sep-11 13:47 

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

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