How can i sent mail with attachment from SharePoint?

Customer sometimes wanna send an email with their documents as attachment. If the documents are stored in a a SharePoint library, there is a small difference than if they are stored in a folder on the server. So this piece of code might help you to send the mail including the attached file from SharePoint library. The important step is to use the WebClient and Download Data method.

[sourcecode language=”csharp”]

WebClient webClient = new WebClient();
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;

fileUrl = “your SharePoint File Path absolute”;
byte[] data = webClient.DownloadData(fileUrl);
MemoryStream fs = new MemoryStream(data);

fileName = “Your filename.xx”;

attachment = new Attachment(fs, fileName);
mail.Attachments.Add(attachment);

[/sourcecode]

Hope it helps you.

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Karsten Schneider 312 Articles
Consultant for Microsoft 365 Applications with a strong focus in Teams, SharePoint Online, OneDrive for Business as well as PowerPlatform with PowerApps, Flow and PowerBI. I provide Workshops for Governance & Security in Office 365 and Development of Solutions in the area of Collaboration and Teamwork based on Microsoft 365 and Azure Cloud Solutions. In his free time he tries to collect tipps and worthy experience in this blog.

1 Comment

Leave a Reply