Solved

C# Outlook.Attachment.Add to attach a document from a url

Posted on 2009-07-12
11
2,084 Views
Last Modified: 2012-06-27
I have an issue where I need to have my web application attach a file from a url (sharepoint url).

My code below will work for a direct file path but I will get an error if I try to do it with a url.  The main reason why I need to be able to do this is because I want to create a custom action in sharepoint and have it send a document as an attachment.

I know I can do this with JavaScript utilizing ActiveX but now days most browser will block activeX controls and it becomes more difficult to support end-users and educate them on how to enable ActiveX

below is my code for calling Outlook.  Please Note for this to work you must Microsoft.Office.Core and Microsoft.Office.Interop.Outlook for it to work
Microsoft.Office.Interop.Outlook.ApplicationClass _MsOutlook = new Microsoft.Office.Interop.Outlook.ApplicationClass();
            Microsoft.Office.Interop.Outlook.NameSpace oNs = null;
            Microsoft.Office.Interop.Outlook.MailItem oMailItem = (Microsoft.Office.Interop.Outlook.MailItem)_MsOutlook.CreateItem(OlItemType.olMailItem);
            oMailItem.Subject = "";
            oMailItem.To = "";
            oMailItem.CC = "";
            oMailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;
            oMailItem.HTMLBody = stBody;
            oMailItem.Attachments.Add(TextBox1.Text, (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, stBody.Length + 1, stDisplayName);
            oMailItem.Display(true);

Open in new window

0
Comment
Question by:thomasm1948
  • 7
  • 3
11 Comments
 
LVL 6

Expert Comment

by:microbolt
ID: 24835762
For it to work you must have the document stored locally on the system before you attach it.  Try having your app download it to an temp folder on your machine and attaching it from there.
0
 
LVL 4

Expert Comment

by:aletjolly
ID: 24835938
0
 

Author Comment

by:thomasm1948
ID: 24841048
I tried downloading the file as you explained but I get an unauthorized error message
0
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 

Author Comment

by:thomasm1948
ID: 24841085
Below is my test code for downloading the document.  If I am able to get this to work then I can simply have my application do a Request.QueryString["item"]; to get the path of any document in the document library
string test2 = "/demsite/MRP Detailed Output/Payment Plan for jan and feb 2009.xlsx";
        string webString = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        string webdoc = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        int LastIndex = webdoc.LastIndexOf("/");
        //tmp.Substring(LastIndex + 1, (tmp.Length - LastIndex - 1));
        webdoc = webdoc.Substring(LastIndex + 1, (webdoc.Length - LastIndex - 1));
        System.Net.WebClient webClient = new System.Net.WebClient();
        webClient.DownloadFile(webString, @"c:\" + webdoc);

Open in new window

0
 

Author Comment

by:thomasm1948
ID: 24844235
I get the following code to work but I get a save as dialog box and I would like to just download the file directly to the file system and then delete it after it is done opening Outlook
try
            {
                int flag=0;
                SPSite site = new SPSite("http://tomkat"); 
                SPWeb web = site.OpenWeb(); 
                web.AllowUnsafeUpdates=true;
                string strContentType="";                 
                SPFileCollection files=folder.Files;
                //"docLib" is name of document library and testFile.doc is the name of file                
                string url = "http://tomkat" + TextBox1.Text;
                SPFile tempFile = web.GetFile(url);
                //Get the extension of File.
                string filename = "http://tomkat" + TextBox1.Text;
                int LastIndex = filename.LastIndexOf("/");
                filename = filename.Substring(LastIndex + 1, (filename.Length - LastIndex - 1));               
                string[] fext = filename.Split('.');
                byte []obj=(byte[])tempFile.OpenBinary();
                // Get the extension of File to determine the file type
                string casestring="";
                if(fext.Length>1)
                {
                    casestring= fext[fext.Length-1];
                }
                //set the content type of file according to extension
                switch(casestring)
                {
                    case "txt": 
                        strContentType = "text/plain";
                        break;
                    case "htm" : strContentType = "text/html";
                        break;
                    case "html" : strContentType = "text/html";
                        break;
                    case "rtf" : strContentType = "text/richtext";
                        break;
                    case "jpg" : strContentType = "image/jpeg";
                        break;
                    case "jpeg": strContentType = "image/jpeg";
                        break;
                    case "gif" : strContentType = "image/gif";
                        break;
                    case "bmp" : strContentType = "image/bmp";
                        break;
                    case "mpg" : strContentType = "video/mpeg";
                        break;
                    case "mpeg": strContentType = "video/mpeg";
                        break;
                    case "avi" : strContentType = "video/avi";
                        break;
                    case "pdf" : strContentType = "application/pdf";
                        break;
                    case "doc" : strContentType = "application/msword";
                        break;
                    case "dot": strContentType = "application/msword";
                        break;
                    case "csv" : strContentType = "application/vnd.msexcel";
                        break;
                    case ".xls": strContentType = "application/vnd.msexcel";
                        break;
                    case ".xlt": strContentType = "application/vnd.msexcel";
                        break;
                    default : strContentType = "application/octet-stream";
                        break;
                }
                Response.ClearContent();
                Response.ClearHeaders();
                Response.AppendHeader("Content-Disposition", "attachment; filename= "+ filename);
                Response.ContentType = strContentType;                
                if (Response.IsClientConnected)
                {
                    Response.BinaryWrite(obj);
                    
                    
                }
                Response.Flush();
                Response.Close();
                Response.End();
            }
            catch(System.Exception ex)
            {
            } 
        }

Open in new window

0
 

Author Comment

by:thomasm1948
ID: 24844251
Here is another piece of code that works with activeX but like I said I prefer not to use it because most web browsers will block it by default

            if (!IsPostBack)
            {
                TextBox1.Text = Request.QueryString["item"];
                
            }
            string s;
            s = "\r\n    <script language='javascript' type='text/javascript' id='MyJS'>\r\n  function SendMail()\r\n  {\r\n  var s = window.location.href.substr(0,window.location.href.indexOf('/',8)) +\r\n      document.getElementById('ctl00_PlaceHolderMain_TextBox1').value;\r\n  var outlookApp = new ActiveXObject('Outlook.Application');\r\n  mailItem = outlookApp.CreateItem(0);\r\n  mailItem.Attachments.Add(s);\r\n  mailItem.display (0);\r\n  window.history.back();\r\n } \r\n</script>";
            Page.RegisterClientScriptBlock("WebsioSendMailScript", s);    

Open in new window

0
 
LVL 6

Expert Comment

by:microbolt
ID: 24844392
What happens when you try to use this code?  WebClient would definable be the best solution to your problem.
string test2 = "/demsite/MRP Detailed Output/Payment Plan for jan and feb 2009.xlsx";
        string webString = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        string webdoc = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        int LastIndex = webdoc.LastIndexOf("/");
        //tmp.Substring(LastIndex + 1, (tmp.Length - LastIndex - 1));
        webdoc = webdoc.Substring(LastIndex + 1, (webdoc.Length - LastIndex - 1));
        System.Net.WebClient webClient = new System.Net.WebClient();
        webClient.DownloadFile(webString, @"c:\" + webdoc);

Open in new window

0
 

Author Comment

by:thomasm1948
ID: 24844421
I get an unauthorized error message
0
 

Author Comment

by:thomasm1948
ID: 24844536
If there is another way to call Outlook and attaching a file without utilizing javascript or any other methods that i tried then I am open to try it.  I prefer to use C# because it is native to SharePoint

Thank you for all of your help
0
 
LVL 6

Accepted Solution

by:
microbolt earned 500 total points
ID: 24844574
Try adding credentials into your call.  Try using the snippet below:

string test2 = "/demsite/MRP Detailed Output/Payment Plan for jan and feb 2009.xlsx";
        string webString = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        string webdoc = "http://tomkat" + "/demsite/Shared Documents/021508.pdf";
        int LastIndex = webdoc.LastIndexOf("/");
        //tmp.Substring(LastIndex + 1, (tmp.Length - LastIndex - 1));
        webdoc = webdoc.Substring(LastIndex + 1, (webdoc.Length - LastIndex - 1));
        System.Net.WebClient webClient = new System.Net.WebClient();
        webClient.Credentials = CredentialCache.DefaultCredentials;
        webClient.DownloadFile(webString, @"c:\" + webdoc);

Open in new window

0
 

Author Comment

by:thomasm1948
ID: 24844651
that seemed to have worked.  

Thank you for all of your help
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Signal R -send data to client: only if they are allowed to see it ? 1 52
Code works but it's slow 28 70
Reading the Web.Config using IIS 7.5? 4 36
Hey Audio! 3 29
Summary In SharePoint 2010 it is easy to create custom color themes to jazz up a site. Theme colors can also be created in PowerPoint 2010 with a few clicks. But how do the chosen colors actually look in the SharePoint site? The attached PowerPoint…
I thought I'd write this up for anyone who has a request to create an anonymous whistle-blower-type submission form created using SharePoint 2010 (this would probably work the same for 2013). It's not 100% fool-proof but it's as close as you can get…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question