One of the ways to send an e-mail from SharePoint as developer, is to make use of the “SPUtility.SendEmail” classes. But unfortunately I did not find any possibility to include an attachment with the help of these classes.
To be able to send attachment I decided to make use of the normal “System.Net.Mail” classes to send a message. Instead of hard coding the SMTP information into the code, I wanted to use the SMTP settings that are configured with the SharePoint Central Administration. These settings are found in the “SPAdministrationWebApplication” class.
Because SharePoint stores it’s files into the content database, we must do a http request to retrieve the attachment. Using the “System.Net.WebClient” is one way to do it and one of the advantages is that you can supply it with the credentials of the user that is trying to send the mail.
You will receive an unauthorized message if you don’t supply a correct set of credentials. It’s probably not a good idea to hardcode the credentials as it will be possible for users to get access to files they are not supposed to. Supplying the WebClient with the “CredentialCache.DefaultNetworkCredentials” worked fine for me on a standard SharePoint environment.
Below is a brief example on how you can send the mail with attachment from code. If you prefer to use the user’s e-mail address instead of the configured SMTP user you can retrieve it with SPControl.GetContextWeb(Context).CurrentUser.Email.
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
//Create the mail message and supply it with from and to info
MailMessage mailMessage = new MailMessage(smtpFrom, insert_receiver);
//Set the subject and body of the message
mailMessage.Subject = insert_subject;
mailMessage.Body = insert_body;
//Download the content of the file with a WebClient
WebClient webClient = new WebClient();
//Supply the WebClient with the network credentials of our user
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
//Download the byte array of the file
byte data = webClient.DownloadData(insert_ attachment_url);
//Dump the byte array in a memory stream because
//we can write it to our attachment
MemoryStream memoryStreamOfFile = new MemoryStream(data);
//Add the attachment
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, insert_filename_attachment, insert_content_type));
//Create the SMTP client object and send the message
SmtpClient smtpClient = new SmtpClient(smtpServer);