Send Email with attachment

using(SPSite site = new SPSite("http://siteurl"))
{
  using(SPWeb web = site.OpenWeb())
   {
       // Check there is an email server configured
        if (SPUtility.IsEmailServerSet(web)) 
        {
            // Get the web app so we can get the email server SP is configured to use
            SPWebApplication webApp = web.Site.WebApplication; 

            // Get the mail server details
            string smtpServerAddress = webApp.OutboundMailServiceInstance.Server.Address;
            string fromAddress = webApp.OutboundMailSenderAddress;

            var email = new MailMessage();
            email.From = new MailAddress(fromAddress);

            // Your code to load the zip file as an SPFile              

            Stream contentStream = spFile.OpenBinaryStream();
            var attachment = new Attachment(contentStream, spFile.Name);
            email.Attachments.Add(attachment);

            email.Subject = "Your email subject";
            email.Body = "Your email body text";

            // Set up the mail server and sent the email
            SmtpClient mailServer = new SmtpClient(smtpServerAddress);
            mailServer.Credentials = CredentialCache.DefaultNetworkCredentials;
            mailServer.Send(email);
        }
   }
}

猜你喜欢

转载自www.cnblogs.com/jackhu88/p/9210047.html