SharePoint custom development to send Attachment in mail
The reference required to send mail.
using System.Net.Mail;Code block to send mail:
MailMessage msg = new MailMessage();
//Contruct attachment URL
string url = Convert.ToString(TargetWeb.Url) + "/" + Constants.CONST_MEMOLIST + "/" + Convert.ToString(MemoItem["Name"]);
//SPFile to get attachment and attach to Mailmessage
SPFile File = TargetWeb.GetFile(url);
msg.Attachments.Add(new Attachment(File.OpenBinaryStream(), File.Name));
msg.To.Add("[email protected]");
msg.Body = "This is an sample email";
string FromAddress = string.Empty;
//SMTP Client to send mail.
SmtpClient smtpClient;
string smtpserverAddress = string.Empty;
Guid CurrentSiteID = TargetWeb.Site.ID; //SitCurrentSite.ID;
SPSecurity.RunWithElevatedPrivileges(delegate() {
using(SPSite elevatedsite = new SPSite(CurrentSiteID)) {
FromAddress = elevatedsite.WebApplication.OutboundMailSenderAddress;
if (string.IsNullOrEmpty(smtpserverAddress)) {
SPOutboundMailServiceInstance smtpserver = elevatedsite.WebApplication.OutboundMailServiceInstance;
if (smtpserver != null) {
smtpserverAddress = smtpserver.Server.Address;
}
}
}
});
msg.From = new MailAddress(FromAddress, DisplayName);
smtpClient = new SmtpClient(smtpserverAddress);
smtpClient.Send(msg);