0

I am trying to attach a file present in a doc library and send it using smtp in client object model. Its in office 365. It throws an exception "The given path's format is not supported". Is there any workaround?

        SmtpClient client = new SmtpClient();
        client.Port = 587;
        client.EnableSsl = true;
        client.Host = "smtp.office365.com";
        client.Timeout = 10000;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("username", "password");

        MailMessage mm = new MailMessage("sender", "reciever", "title", "body");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

        System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment("url");// url of the file present in document library
        mm.Attachments.Add(attachment);`

2 Answers 2

0

You could also use a memory stream with app only permissions

Then you need to use OpenBinaryStream. Note that the streams needs to be open on client.Send(), so you need to deal with that if you want to send all attachments in the same email...

private void MailFiles(string url, string libraryName)
{
    var uri = new System.Uri(url);
    string realm = TokenHelper.GetRealmFromTargetUrl(uri);
    var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, uri.Authority, realm).AccessToken;
    using (var appCtx = TokenHelper.GetClientContextWithAccessToken(uri.ToString(), token))
    {

        var docs = appCtx.Web.Lists.GetByTitle(libraryName);
        var qry = CamlQuery.CreateAllItemsQuery();

        var srcItems = docs.GetItems(qry);

        appCtx.Load(srcItems, icol => icol.Include(i => i.FileSystemObjectType, i => i["FileRef"], i => i.File));
        appCtx.Load(docs, l => l.RootFolder);
        appCtx.ExecuteQuery();

        foreach (var item in srcItems)
        {
            Microsoft.SharePoint.Client.File file = item.File;
            ClientResult<Stream> data = file.OpenBinaryStream();

            appCtx.Load(file);
            appCtx.ExecuteQuery();

            using (var memory = new MemoryStream())
            {
                byte[] buffer = new byte[1024 * 64];
                int nread = 0;
                while ((nread = data.Value.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memory.Write(buffer, 0, nread);
                }
                memory.Seek(0, SeekOrigin.Begin);


                SmtpClient client = new SmtpClient();
                client.Port = 587;
                client.EnableSsl = true;
                client.Host = "smtp.office365.com";
                client.Timeout = 10000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential("user", "password");

                MailMessage mm = new MailMessage("sender", "to", "title", "body");
                mm.BodyEncoding = UTF8Encoding.UTF8;
                mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(memory, file.Name);
                mm.Attachments.Add(attachment);
                client.Send(mm);
            }
        }
    }
}
0

You can not give the simple url to download the file from Sharepoint online. As it requires some authentication from Client.

You can download the file first to a temp location, then attach that file to your email and after that delete that file from your temp location.

For downloading file check this article.

Code to download file using CSOM:

var securePassword = new SecureString();
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            using (ClientContext clientContext = new ClientContext(targetSite))
            {
                clientContext.Credentials = onlineCredentials;
                Web web = clientContext.Web;
                List documents = web.Lists.GetByTitle("Documents");
                clientContext.Load(documents);
                clientContext.ExecuteQuery();
                ListItemCollection objListItemCollection = documents.GetItems(new CamlQuery());
                clientContext.Load(objListItemCollection,
                items => items.Include(item => item.Id,
                item => item["UniqueId"],
                item => item["LinkFilename"],
                item => item["FileRef"],
                item => item["EncodedAbsUrl"],
                item => item["DocIcon"]));
                clientContext.ExecuteQuery();

                FileInformation fileInformation =
               Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, (string)objListItemCollection[0]        ["FileRef"]);
                using (var fileStream = System.IO.File.Create(@"C:\File.txt"))
                {
                    fileInformation.Stream.CopyTo(fileStream);
                }
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.